在破坏的对象上移动构造函数
Move constructor on destructed object?
我有一块代码
#include <iostream>
class A {
public:
A() {
std::cout << "Default constructor" << std::endl;
}
A(const A & other)
{
std::cout << "Copy constructor" << std::endl;
}
A(A && other)
{
std::cout << "Move constructor" << std::endl;
}
~A()
{
std::cout << "Destructor" << std::endl;
}
private:
int i;
};
A && f()
{
return A();
}
int main() {
A a = f();
}
我尝试运行它,而输出结果为
Default constructor
Destructor
Move constructor
Destructor
我的问题是,为什么在移动的构造函数之前称为灾难?这是否也意味着第二个对象是用破坏值构建的?
从A && f()
返回本地变量的问题与A & f()
相同。它们都是参考。当您在main()
中构造a
时,局部变量已被破坏。这导致引用被破坏的实例导致不确定的行为。
如果您想将A()
从f()
移动到main
中的a
,只需按值返回即可。尝试使用以下内容:
A f() {
return A();
}
第一个A
对象是在f
的调用堆栈帧中创建的。因此,当f
将控件返回到main
时,将必须破坏f
中创建的所有堆栈对象。这就是为什么称为第一个破坏者的原因。
相关文章:
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- 为什么调用复制构造函数而不是移动构造函数?
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 移动构造函数和右值引用
- 为什么 std::memmove 中联合的默认非平凡移动构造函数C++?
- 具有专用化的模板类中的可靠条件复制和移动构造函数
- C++:为什么不调用移动构造函数?
- 移动构造函数永远不会被调用
- C++:关于使用 Stroustrup 示例移动构造函数/赋值的问题
- 运算符+ 的规范实现涉及额外的移动构造函数
- C ++为什么在移动构造函数中需要移动/前进
- 为什么在删除"移动构造函数"时使用"复制构造函数"?
- 为什么这里不调用移动构造函数?
- 隐式移动构造函数
- 如何为具有私有成员的派生类实现移动构造函数
- 为什么不调用移动构造函数
- 是否可以避免在以下代码中复制/移动构造函数的需要?