Why destructor of a moved from object is invoked?

百般思念 提交于 2019-12-22 04:35:47

问题


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?

回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!