Is std::vector copying the objects with a push_back?

后端 未结 8 1695
夕颜
夕颜 2020-11-28 00:46

After a lot of investigations with valgrind, I\'ve made the conclusion that std::vector makes a copy of an object you want to push_back.

Is that really true ? A vect

相关标签:
8条回答
  • 2020-11-28 01:40

    From C++11 onwards, all the standard containers (std::vector, std::map, etc) support move semantics, meaning that you can now pass rvalues to standard containers and avoid a copy:

    // Example object class.
    class object
    {
    private:
        int             m_val1;
        std::string     m_val2;
    
    public:
        // Constructor for object class.
        object(int val1, std::string &&val2) :
            m_val1(val1),
            m_val2(std::move(val2))
        {
    
        }
    };
    
    std::vector<object> myList;
    
    // #1 Copy into the vector.
    object foo1(1, "foo");
    myList.push_back(foo1);
    
    // #2 Move into the vector (no copy).
    object foo2(1024, "bar");
    myList.push_back(std::move(foo2));
    
    // #3 Move temporary into vector (no copy).
    myList.push_back(object(453, "baz"));
    
    // #4 Create instance of object directly inside the vector (no copy, no move).
    myList.emplace_back(453, "qux");
    

    Alternatively you can use various smart pointers to get mostly the same effect:

    std::unique_ptr example

    std::vector<std::unique_ptr<object>> myPtrList;
    
    // #5a unique_ptr can only ever be moved.
    auto pFoo = std::make_unique<object>(1, "foo");
    myPtrList.push_back(std::move(pFoo));
    
    // #5b unique_ptr can only ever be moved.
    myPtrList.push_back(std::make_unique<object>(1, "foo"));
    

    std::shared_ptr example

    std::vector<std::shared_ptr<object>> objectPtrList2;
    
    // #6 shared_ptr can be used to retain a copy of the pointer and update both the vector
    // value and the local copy simultaneously.
    auto pFooShared = std::make_shared<object>(1, "foo");
    objectPtrList2.push_back(pFooShared);
    // Pointer to object stored in the vector, but pFooShared is still valid.
    
    0 讨论(0)
  • 2020-11-28 01:44

    if you want not the copies; then the best way is to use a pointer vector(or another structure that serves for the same goal). if you want the copies; use directly push_back(). you dont have any other choice.

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