考虑以下代码:
struct foo {
std::string id;
};
int main() {
std::vector<foo> v;
{
foo tmp;
v.push_back(std::move(tmp));
}
}
在演示的代码中:
- 将调用类
foo
的默认构造函数来构造对象tmp
。 - 类
foo
的 move 构造函数将在语句v.push_back(std::move(tmp));
中调用。 class foo
的析构函数将被调用两次。
问题:
- 为什么 moved from 对象的析构函数被调用两次?
- 真正从被 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::string
。 std::string
的 move 构造函数通常获取存储实际字符串的移出对象中的内存块的所有权,并将移出对象设置为有效但未指定的状态(实际上,可能是一个空字符串)。
关于c++ - 为什么调用从对象移出的析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24582283/