问题
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:
- The default constructor of class
foo
is going to be invoked for the construction of objecttmp
. - The move constructor of class
foo
is going to be invoked in the statementv.push_back(std::move(tmp));
. - The destructor of
class foo
is going to be invoked twice.
Questions:
- Why the destructor of a moved from object is called twice?
- What is moved from the object that is being moved really?
回答1:
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).
来源:https://stackoverflow.com/questions/24582283/why-destructor-of-a-moved-from-object-is-invoked