Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why destructor of a moved from object is invoked?

Tags:

c++

c++11

move

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:

  1. The default constructor of class foo is going to be invoked for the construction of object tmp.
  2. The move constructor of class foo is going to be invoked in the statement v.push_back(std::move(tmp));.
  3. The destructor of class foo is going to be invoked twice.

Questions:

  1. Why the destructor of a moved from object is called twice?
  2. What is moved from the object that is being moved really?
like image 844
101010 Avatar asked Jul 05 '14 01:07

101010


1 Answers

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).

like image 154
T.C. Avatar answered Sep 23 '22 13:09

T.C.