在下面的场景中(它只是一个 sscce ),我怎样才能避免复制构造函数(注释掉的代码)?
typedef boost::variant< std::vector<int>,
std::vector<char>,
std::vector<float>
> VecRMPType;
struct Widgets{
int widget_id;
VecRMPType rmps_vec ;
template< typename T>
Widgets(int wid, T rmps_vec_ ) :
widget_id(wid), rmps_vec( std::move(rmps_vec_) )
{
}
Widgets( const Widgets&& wids_ ) :
widget_id( wids_.widget_id), rmps_vec(wids_.rmps_vec )
{
}
/*
// This constructor I want to disable.
Widgets( const Widgets& wids_ ):
widget_id( wids_.widget_id), rmps_vec( std::move(wids_.rmps_vec) )
{
}
*/
};
class Layers {
int symb_id;
std::vector< Widgets > widgets ;
Layers(const Layers& ) ;
Layers& operator=(const Layers& ) ;
public:
Layers(int sid_, std::vector<Widgets> wids_ ):
symb_id(sid_), widgets(std::move(wids_) )
{ }
Layers(const Layers&& L_ ):
symb_id(L_.symb_id), widgets( std::move(L_.widgets) )
{ }
};
目前,编译器抛出一个 error
我是否遗漏了一些明显的东西或有任何误解?
PS:我尝试在SO上搜索相关内容,但仍然找不到,如果重复,请评论,我会删除问题。
最佳答案
移动构造函数通常如下所示:
Foo(Foo&& other)
您还必须在组件上显式使用 std::move
。
然后,删除
复制构造函数:
Foo(Foo const&) = delete;
尽管如果您有用户提供的移动构造函数,则简单地省略它们也是可以接受的。
关于c++ - 如何禁止复制构造函数并仅使用移动构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23973273/