Consider the following piece of code:
struct foo {
std::string id;
};
int main() {
std::vector<foo> v;
{
foo tmp;
v.push_back(std::move(tmp));
}
}
LIVE DEMO
In the piece of code demonstrated:
foo
is going to be invoked for the construction of object tmp
.foo
is going to be invoked in the statement v.push_back(std::move(tmp));
.class foo
is going to be invoked twice.Questions:
Why the destructor of a moved object is called twice?
The first destructor destroys the moved-from tmp
when it goes out of scope at the first }
in main()
. The second destructor destroys the move-constructed foo
that you push_back
'd into v
at the end of main()
when v
goes out of scope.
What is moved from the object that is being moved really?
The compiler-generated move constructor move-constructs id
, which is a std::string
. A move constructor of std::string
typically takes ownership of the block of memory in the moved-from object storing the actual string, and sets the moved-from object to a valid but unspecified state (in practice, likely an empty string).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With