在 boost::不可复制类中,设置 move 构造函数 "=default" 不会编译?



考虑以下代码。为了使其编译,我必须为move构造函数提供一个主体。有"TestClass (TestClass&和其他)= default"编译时不会出现"&;TestClass::TestClass(TestClass&&)"被隐式删除的错误,因为默认定义格式错误:">

为什么会这样?为什么它不能算出违约呢?

#include <iostream>
#include <optional>
#include <boost/noncopyable.hpp>
class TestClass : public boost::noncopyable {
public:
TestClass() {
std::cout << "Constructed...n";
}
TestClass(TestClass&& other) = default;
//TestClass(TestClass&& other)  {
//    std::cout << "Move constructor...n";
//}
TestClass& operator=(TestClass&& other)  {
std::cout << "Move assignment...n";
return *this;
}
};
TestClass doThing() {
std::optional<TestClass> tc = std::make_optional<TestClass>(TestClass{});
return std::move(*tc);
}
int main() {
const TestClass t = doThing();
}

https://godbolt.org/z/3f5zTT6a9

boost::noncopyable来源于c++ 11之前。所以也许这个名字并没有让这一点变得明显,但它不仅使类不可复制,而且使它不可移动(只有在c++ 11中才添加了move语义)。如果基类不能移动,那么move构造函数的默认实现是不可能的。

并且private继承时应该使用它,而不是public

最新更新