C++:为什么不调用移动构造函数?
C++ : Why is move constructor not getting called?
我正在试验以下代码:
#include <iostream>
#include <utility>
using namespace std;
class A
{
int data;
public:
A(): data{0}
{
}
A(const A& other)
{
print(other);
}
A(A&& other)
{
print(other);
}
void print(const A& other) const
{
cout << "In print 1" << endl;
}
void print(const A&& other) const
{
cout << "In print 2" << endl;
}
};
int main() {
A a0;
A a1(a0);
A a2(A());
return 0;
}
我期望输出是:
In print 1
In print 1
但是,实际输出为:
In print 1
显然,移动构造函数不会被调用。为什么会这样?在a2
建设过程中,它的位置叫什么?
因为A a2(A());
实际上是函数声明,而不是对象的声明。看到这个:
我对值初始化的尝试被解释为函数声明,为什么 A a((((; 解决它?
如果要查看移动构造函数,请执行以下操作:
A a2((std::move(A())));
相关文章:
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- 为什么调用复制构造函数而不是移动构造函数?
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 具有已删除移动和复制构造函数的类的就地构造
- 移动构造函数和右值引用
- 使用移动调用对等构造函数unique_ptr默认构造函数
- 为什么 std::memmove 中联合的默认非平凡移动构造函数C++?
- 具有专用化的模板类中的可靠条件复制和移动构造函数
- 构造函数采用std::string_view与std::string并移动
- C++:为什么不调用移动构造函数?
- 了解构造函数在移动、复制、赋值语义中的行为
- 没有移动的构造函数移动课程
- 引用绑定和复制构造函数/移动构造函数
- 构造函数移动
- C++ 向量实现 - 移动构造函数 - 移动与前进
- 我真的必须取消移动构造函数/移动结构中的所有成员还是只是指针
- 将类(没有默认构造函数)移动到另一个类的move构造函数中