【发布时间】:2017-06-21 17:58:14
【问题描述】:
引自C++ Primer
如果我们明确要求编译器通过 使用
= default,编译器无法移动所有 成员,则移动操作将被定义为删除移动构造函数被定义为删除如果 类有一个成员,它定义了自己的复制构造函数,但也没有 定义一个移动构造函数,或者如果该类有一个没有定义它的成员 自己的复制操作,编译器无法合成移动 构造函数
有些代码似乎违反了这条规则:
#include <utility>
#include <iostream>
struct X {
X() = default;
X(const X&) { std::cout << "X(const X&)" << std::endl; }
int i;
};
struct hasX {
hasX() = default;
hasX(const hasX &) = delete;
hasX(hasX &&) = default;
X mem;
};
int main()
{
hasX hx, hx2 = std::move(hx); //output is X(const X&)
}
X 没有定义移动构造函数,编译器无法为它合成一个。
根据上面的规则,hasX的移动构造函数被删除了。
但是,因为hasX的拷贝构造函数被删除了,hx2 = std::move(hx)必须调用移动构造函数输出"X(const X&)",这说明hasX的移动构造函数已经定义,它使用X的拷贝构造函数移动”。这似乎违反了上面的规则。
那么,是不是在 C++ 标准中定义或只是一个编译器实现?
我测试的编译器:VS2015 和a online compiler
感谢您的帮助!
【问题讨论】:
标签: c++ c++11 constructor