以下是代码:
#include <iostream>
#include <memory>
#include <string>
using namespace std;
struct Foo {
string tag;
Foo(string t): tag(t){
cout << "Foo:" << tag << endl;
}
~Foo() {
cout << "~Foo:" << tag << endl;
}
};
struct Bar {
Foo&& foo;
};
struct Baz{
Foo&& foo;
Baz(Foo&& f):foo(std::move(f)){
}
};
int main() {
Bar bar{Foo("Bar")};
Baz baz{Foo("Baz")};
cin.get();
}
结果(g++ 7.1.0):
Foo:Bar
Foo:Baz
~Foo:Baz
我们可以看到,
bar
成功地扩展了临时 Foo
的生命周期,但是baz
没有成功。这两者之间有什么区别?我该如何正确实现 Baz
的构造函数?
编辑:实际上 VC++2017 给出:
Foo:Bar
~Foo:Bar
Foo:Baz
~Foo:Baz
所以我猜整个事情都不可靠。
~Foo:Bar
将是一个严重的编译器错误。 - M.M~Foo:Bar
,您能再次检查一下吗? - M.M~Foo:Bar
不像~Foo:Baz
那样立即被调用。 - songyuanyao~Foo:Bar
不会立即调用。 - songyuanyao