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

后端 未结 8 1728
夕颜
夕颜 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 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> myPtrList;
    
    // #5a unique_ptr can only ever be moved.
    auto pFoo = std::make_unique(1, "foo");
    myPtrList.push_back(std::move(pFoo));
    
    // #5b unique_ptr can only ever be moved.
    myPtrList.push_back(std::make_unique(1, "foo"));
    
    
    

    std::shared_ptr example

    std::vector> 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(1, "foo");
    objectPtrList2.push_back(pFooShared);
    // Pointer to object stored in the vector, but pFooShared is still valid.
    
        

    提交回复
    热议问题