【发布时间】:2016-03-18 00:21:25
【问题描述】:
我有下面的代码,它给了我以下输出:
构造流 s1
破坏流 s1
输出1
测试
构建流 s2
破坏流 s2
测试
#include <iostream>
#include <utility>
#include <memory>
#include <string>
using std::cout;
class Stream {
public:
Stream(const std::string &name) : s(name) {
cout << "Constructing stream " << name << std::endl;
}
virtual ~Stream(){
cout << "Destructing stream " << s << std::endl;
}
friend Stream &&operator<<(Stream &&rhs, const std::string &str) {
cout << str << std::endl;
return std::move(rhs);
}
std::string s;
};
Stream &&getStream(const std::string &name){
Stream stream(name);
return std::move(stream);
}
int main(int argc, const char **argv) {
getStream("s1") << "Output1" << "Test";
getStream("s2") << "Test";
}
我对输出的期望是这样的:
构造流 s1
输出 1
测试
破坏流 s1
构造流 s2
测试
破坏流 s2
为什么在
【问题讨论】:
-
代码具有未定义的行为,因为您正在返回对局部变量的引用。
-
对 Stream getStream(const std::string &name) 的更改将行为更改为:构造流 s1 破坏流 s1 输出 1 测试破坏流 s1 构造流 s2 破坏流 s2 测试破坏流 s2
标签: c++ c++11 constructor operator-overloading destructor