Should I use C++11 emplace_back with pointers containers?

前端 未结 2 709
无人及你
无人及你 2020-12-24 12:50

Having a usual Base -> Derived hierarchy, like:

class Fruit { ... };
class Pear : Fruit { ... };
class Tomato : Fruit { ... };

std::vector m         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 13:24

    Don't use raw pointers, use std::unique_ptr like this:

    std::vector> m_fruits;
    

    And as you can't copy construct a std::unique_ptr you must use emplace_back (although you can use push_back with std::move).

    m_fruits.emplace_back(new Pear());
    m_fruits.emplace_back(new Tomato());
    

    Edit:

    As it appears that using std::vector>::emplace_back and new can leak if the std::vector needs and fails to reallocate memory, my recommended approach (until C++14 introduces std::make_unique) is to use push_back like this:

    m_fruits.push_back(std::unique_ptr(new Pear()));
    m_fruits.push_back(std::unique_ptr(new Tomato()));
    

    Or using std::make_unique:

    m_fruits.push_back(std::make_unique());
    m_fruits.push_back(std::make_unique());
    

提交回复
热议问题