【问题标题】:How to disallow the copy constructor and use only move constructor?如何禁止复制构造函数并仅使用移动构造函数?
【发布时间】:2014-05-31 17:34:06
【问题描述】:

在以下情况下(它只是一个 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上搜索相关的东西,但仍然找不到,如果重复,请评论,我会删除问题。

【问题讨论】:

  • 你不能从 const 右值引用中移动,从你的移动构造函数参数中去掉 const。然后你必须std::move初始化列表中的每个数据成员。
  • 根据错误,复制构造函数被“禁用”(如预期的那样)。那你到底在问什么?
  • @juanchopanza 对不起,我的建议让我在没有复制构造函数的情况下工作,我只是想避免深度复制。

标签: c++ c++11 copy-constructor


【解决方案1】:

移动构造函数通常看起来像:

Foo(Foo&& other)

您还必须在组件上显式使用std::move

然后,delete 复制构造函数:

Foo(Foo const&) = delete;

尽管如果您有用户提供的移动构造函数,则简单地省略它们也是可以接受的。

【讨论】:

    猜你喜欢
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多