Why destructor of a moved from object is invoked?
c++, c++11, move
Solution
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).
Problem
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 object `tmp`. - The move constructor of class `foo` is going to be invoked in the statement `v.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?