Getting around copy semantics in C++

后端 未结 1 2105
攒了一身酷
攒了一身酷 2021-02-19 08:29

Please consider this code:

class A
{

};

int main()
{
    std::vector test;
    test.push_back(A());
}

The constructor and destructor

相关标签:
1条回答
  • 2021-02-19 08:34

    Use emplace_back.

    std::vector<A> test;
    test.emplace_back();
    //test.emplace_back(constructor, parameters);
    

    This way, A will be constructed in-place, so no copy or move will occur.

    Edit: To clarify on the comments on the question - No, this will not change from push_back if you pass it a temporary. For instance,

    test.emplace_back(A{});
    

    Will, in C++11, cause a temporary A to be constructed, moved and destroyed, as if you used push_back.

    0 讨论(0)
提交回复
热议问题