For the code below:
#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();
}
result:
Foo:Bar
Foo:Baz
~Foo:Baz
We can see that bar
successfully extend the lifetime of a temporary Foo but baz
failed to do so. What is the difference between the two? How can I implement the constructor of Baz
correctly?
Edit: actually VC++2017 gives:
Foo:Bar
~Foo:Bar
Foo:Baz
~Foo:Baz
So I guess the whole thing is not reliable. Is there any way to make sure that member not destroyed when the holder is alive?
Aucun commentaire:
Enregistrer un commentaire