为什么调用从对象移动的析构函数? [英] Why destructor of a moved from object is invoked?

查看:106
本文介绍了为什么调用从对象移动的析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑下面的代码:

  struct foo {
std :: string id;
};

int main(){
std :: vector< foo> v;

{
foo tmp;
v.push_back(std :: move(tmp));
}
}

LIVE DEMO



在代码段中展示:


  1. foo 的默认构造函数将被调用来构造对象 tmp

  2. foo 将在语句 v.push_back(std :: move(tmp)); 中调用。

  3. class foo 的析构函数将被调用两次。

问题:


  1. 为什么从对象移动的析构函数被调用两次? li>
  2. 从正在移动的对象移动的是什么?


解决方案

为什么被移动对象的析构函数被调用两次?当 main()中的第一个} 超出范围时,从 tmp 。第二个析构函数破坏了移动构造的 foo ,将 push_back '转换为 v 超出范围时, main() b
$ b


从正在移动的对象中移动什么?


编译器生成的移动构造函数move-constructs id ,它是一个 std :: string std :: string 的移动构造函数通常获取存储实际字符串的移动对象中的内存块的所有权,并将移动的对象设置为有效但未指定状态(实际上,可能是一个空字符串)。


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?

解决方案

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

这篇关于为什么调用从对象移动的析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆