用默认构造函数生成的c++移动构造函数
c++ move constructor generated with default constructor
看这个问题,它提到了 c++ 11和以后只提到:
如果没有用户声明的复制构造函数、复制赋值操作符或析构函数,并且生成的移动构造函数是有效的(例如,如果它不需要分配常量成员)(§12.8/10),则自动生成move构造函数。
如果我有下面的代码:
class Y
{
public:
Y(const Y&) {}
};
struct hasY {
hasY() = default;
hasY(hasY&&) = default;
Y mem;
};
hasY hy, hy2 = std::move(hy); //this line fails as expected as Y has a user-defined copy constructor.
现在如果我给Y添加默认构造函数:
Y() {}
错误消失。
它在哪里说默认构造函数导致move构造函数的创建?
(使用VS 2015 update 2)
class Y
{
public:
Y(const Y&) {}
};
这个类没有默认构造函数,所以
struct hasY {
hasY() = default;
hasY(hasY&&) = default;
Y mem; // << requires default ctor
};
你得到的错误与move构造函数无关:
prog.cpp: In function 'int main()':
prog.cpp:13:7: error: use of deleted function 'hasY::hasY()'
hasY hy;
^
prog.cpp:8:5: note: 'hasY::hasY()' is implicitly deleted because the default definition would be ill-formed:
hasY() = default;
http://ideone.com/u46GWS 与move构造函数无关,它是关于默认构造函数的。试试这个:
class Y
{
public:
Y(const Y&) {}
};
struct hasY {
hasY() = default;
hasY(hasY&&) = default;
Y mem;
};
hasY hy; // This will cause an error because there is no default constructor
现在,如果您添加默认构造函数:Y(){}
,错误将消失。
@M。M注释说,在这种情况下将调用复制构造函数。
你可以试试下面的代码:
class Y{
public:
Y(){std::cout << "Default constructorn";}
Y(const Y&) {std::cout << "Copy constructorn";}
};
struct hasY {
hasY() = default;
hasY(hasY&&) = default;
Y mem;
};
int main(){
hasY hy;
hasY h=std::move(hy);
}
它将打印:
默认构造函数
复制构造函数
如果你想让类不可移动,你应该自己删除move构造函数Y(Y&&)=delete;
哪里说默认构造函数导致move构造函数的创建?
move构造函数的创建与默认构造函数是否存在之间没有关系。
来自c++ 11标准:
12.8复制和移动类对象
…如果类X的定义没有显式声明move构造函数,则隐式声明move构造函数默认当且仅当
- X没有用户声明的复制构造函数
- X没有用户声明的复制赋值操作符
- X没有用户声明的move赋值操作符
- X没有用户声明的析构函数,并且
- move构造函数不会被隐式定义为删除。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 奇怪的构造函数行为