How to enforce move semantics when a vector grows?

后端 未结 3 890
花落未央
花落未央 2020-11-22 01:43

I have a std::vector of objects of a certain class A. The class is non-trivial and has copy constructors and move constructors defined.

3条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 02:27

    It seems, that the only way (for C++17 and early), to enforce std::vector use move semantics on reallocation is deleting copy constructor :) . In this way it will use your move constructors or die trying, at compile time :).

    There are many rules where std::vector MUST NOT use move constructor on reallocation, but nothing about where it MUST USE it.

    template
    class move_only : public T{
    public:
       move_only(){}
       move_only(const move_only&) = delete;
       move_only(move_only&&) noexcept {};
       ~move_only() noexcept {};
    
       using T::T;   
    };
    

    Live

    or

    template
    struct move_only{
       T value;
    
       template&&, Arg >
                && !std::is_same_v&, Arg >
        >>
       move_only(Arg&& arg, Args&&... args)
          :value(std::forward(arg), std::forward(args)...)
       {}
    
       move_only(){}
       move_only(const move_only&) = delete;   
       move_only(move_only&& other) noexcept : value(std::move(other.value)) {};    
       ~move_only() noexcept {};   
    };
    

    Live code

    Your T class must have noexcept move constructor/assigment operator and noexcept destructor. Otherwise you'll get compilation error.

    std::vector> vec;
    

提交回复
热议问题