How to enforce move semantics when a vector grows?

后端 未结 3 832
花落未央
花落未央 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条回答
  •  走了就别回头了
    2020-11-22 02:26

    Interestingly, gcc 4.7.2's vector only uses move constructor if both the move constructor and the destructor are noexcept. A simple example:

    struct foo {
        foo() {}
        foo( const foo & ) noexcept { std::cout << "copy\n"; }
        foo( foo && ) noexcept { std::cout << "move\n"; }
        ~foo() noexcept {}
    };
    
    int main() {
        std::vector< foo > v;
        for ( int i = 0; i < 3; ++i ) v.emplace_back();
    }
    

    This outputs the expected:

    move
    move
    move
    

    However, when I remove noexcept from ~foo(), the result is different:

    copy
    copy
    copy
    

    I guess this also answers this question.

提交回复
热议问题