簡體   English   中英

如何禁止復制構造函數並僅使用move構造函數?

[英]How to disallow the copy constructor and use only move constructor?

在以下情況下(它只是一個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) )
        { }
 };

當前,編譯器拋出錯誤

我是否缺少明顯的東西或有任何誤解?

PS:我嘗試在SO上搜索相關內容,但仍然找不到,如果重復,請發表評論,我將刪除問題。

移動構造函數通常如下所示:

Foo(Foo&& other)

您還必須在組件上顯式使用std::move

然后, delete副本構造函數:

Foo(Foo const&) = delete;

盡管如果您有一個用戶提供的move構造函數,則簡單地省略它們也是可以接受的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM