Insert into vector having objects without copy constructor

后端 未结 4 1680
执笔经年
执笔经年 2020-12-08 10:53

I have a class whose copy constructors are explicitly deleted (because A uses pointers internally and I don\'t want to fall into shallow copy pitfalls):

clas         


        
4条回答
  •  醉梦人生
    2020-12-08 11:39

    You should add move constructor - because std::vector::emplace_back may do relocation which requires copy/move constructor. Or just use std::deque.

    LIVE DEMO

    #include 
    #include 
    using namespace std;
    
    struct NoCopyNoMove
    {
        NoCopyNoMove(const NoCopyNoMove&) = delete;
        NoCopyNoMove& operator=(const NoCopyNoMove&) = delete;
        NoCopyNoMove(NoCopyNoMove&&) = delete;
        NoCopyNoMove& operator=(NoCopyNoMove&&) = delete;
    
        NoCopyNoMove(int){};
    };
    
    struct OnlyMove
    {
        OnlyMove(const OnlyMove&) = delete;
        OnlyMove& operator=(const OnlyMove&) = delete;
        OnlyMove(OnlyMove&&) noexcept {}
        OnlyMove& operator=(OnlyMove&&) noexcept {}
    
        OnlyMove(int){};
    };
    
    int main()
    {
        deque x;
        x.emplace_back(1);
    
        vector y;
        y.emplace_back(1);
    }
    

    § 23.2.3 Table 101 — Optional sequence container operations

    a.emplace_back(args) [...]

    Requires: T shall be EmplaceConstructible into X from args. For vector, T shall also be MoveInsertable into X.

提交回复
热议问题