C++ vector push_back

前端 未结 7 903
旧时难觅i
旧时难觅i 2020-12-23 22:03

What is the proper way of pushing a new object element onto a std::vector? I want the data to be allocated in the vector. Will this copy the object newrad

相关标签:
7条回答
  • 2020-12-23 22:41

    In addition to the other answers that verify that the object is copied into the container when using push_back via calls to the copy constructor, you might also keep in mind the new emplace_back functionality added with c++0x.

    Calling emplace_back allows you to bypass the creation of any temporary objects and have the object constructed in-place inside the container directly. emplace_back is a varardic template function that accepts the parameters you would pass to the constructor of your object, so in this case:

    std::vector<Radio> m_radios;
    m_radios.emplace_back(radioNum);
    

    will not create any intermediate temporaries. This can be helpful if your objects are expensive to copy.

    Hope this helps.

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