尝试使用不可复制(私有复制构造函数)但可移动的对象时,出现编译错误g++ (GCC) 4.7.2
但未出现编译错误。对我来说,我的示例看起来与 SO 和其他地方的许多其他示例相同。错误消息使它看起来像结构不是“直接可构造”的问题 - 我不知道这意味着什么,所以我不确定为什么一个对象需要“直接构造”才能被推回。MSVC-2012
std::vector::push_back
#include <vector>
#include <memory>
struct MyStruct
{
MyStruct(std::unique_ptr<int> p);
MyStruct(MyStruct&& other);
MyStruct& operator=(MyStruct&& other);
std::unique_ptr<int> mP;
private:
// Non-copyable
MyStruct(const MyStruct&);
MyStruct& operator=(const MyStruct& other);
};
int main()
{
MyStruct s(std::unique_ptr<int>(new int(5)));
std::vector<MyStruct> v;
auto other = std::move(s); // Test it is moveable
v.push_back(std::move(other)); // Fails to compile
return 0;
}
给出错误
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/type_traits: In instantiation of ‘struct std::__is_direct_constructible_impl<MyStruct, const MyStruct&>’:
... snip ...
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/stl_vector.h:900:9: required from ‘void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = MyStruct; _Alloc = std::allocator<MyStruct>; std::vector<_Tp, _Alloc>::value_type = MyStruct]’
main.cpp:27:33: required from here
main.cpp:16:5: error: ‘MyStruct::MyStruct(const MyStruct&)’ is private
各种答案的简单解决方法:
- 使用
MyStruct(const MyStruct&) = delete;
而不是private ctor
破解 - 继承
boost::noncopyable
(或另一个具有私有 ctor 的类)