c++ - 为什么调用从对象移出的析构函数?

标签 c++ c++11 move

考虑以下代码:

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 的 move 构造函数将在语句 v.push_back(std::move(tmp)); 中调用。
  3. class foo 的析构函数将被调用两次。

问题:

  1. 为什么 moved from 对象的析构函数被调用两次?
  2. 真正从被 move 的对象中 move 了什么?

最佳答案

Why the destructor of a moved object is called twice?

第一个析构函数在 main() 的第一个 处超出范围时销毁移出的 tmp。第二个析构函数销毁 move 构造的 foo,您在 main() 的末尾 push_back 进入 v > 当 v 超出范围时。

What is moved from the object that is being moved really?

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

关于c++ - 为什么调用从对象移出的析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24582283/

相关文章:

c++ - 是否可以通过 NM 仅打印用户定义的变量?

c++ - 使用 Eigen 和 std::vector 的 SIGSEGV

c++ - sizeof 和 alignof 有什么区别?

c++ - 连通分量程序产生不正确的输出

audio - applescript:使用Finder move 文件时避免声音

c++ - 将数据移入函数然后返回到它的来源时是否存在任何未定义的行为问题?

c++ - 如何告诉git我的本地目录是远程树中的特定目录

c++类为什么需要main?

c++ - reinterpret_cast 会导致未定义的行为吗?

c++ - 将参数传递给构造函数和成员函数时 move 或复制