std::vector inserts a copy or reference of an object?

12,667

Solution 1

will a reference be inserted into the vector or a copy of this object?

Copy (which means that your class should be copy-able otherwise compiler error).

Clarification: References cannot be assigned in std::vector<>. Also, here object has broader sense, it can be a normal variable or a pointer, but std::vector<> accepts only copy.

Update: Post C++11, most of the standard containers offer std::move() of the object using "rvalue based API methods"; where a copy may not be performed.

Solution 2

If you have an object of type T that you have dynamically allocated and you push a pointer to the object onto a std::vector<T*>, then a copy of the pointer is pushed. If you dereference the pointer and push the result onto a std::vector<T>, then a copy of the object is made. Collections always make copies. So collections of pointers make copies of the pointer and collections of class instances make copies of the instances themselves (using copy construction IIRC).

Solution 3

Have you checked the reference:

void push_back ( const T& x );

Add element at the end

Adds a new element at the end of the vector, after its current last element. The content of this new element is initialized to a copy of x.

This effectively increases the vector size by one, which causes a reallocation of the internal allocated storage if the vector size was equal to the vector capacity before the call. Reallocations invalidate all previously obtained iterators, references and pointers

Share:
12,667
Shai
Author by

Shai

Updated on June 05, 2022

Comments

  • Shai
    Shai almost 2 years

    Lets say I have an object that I dynamically allocated. If I push it into a STL vector, will a reference be inserted into the vector or a copy of this object?

    It's a general question. For example:

    class vec {
    vector<obj> vec;
    void addToVec(obj a) {
        // insert a into vec
     }
      ...
      ...
      ...
     }
    
    obj* a = new obj;
     vec* v = new vec;
     vec.addToVec(a); 
    

    If I delete v, will object a die as well?

  • matiu
    matiu over 12 years
    I was surprised, I thought the compiler would optimize away the copy operation in some cases, but found it didn't: ideone.com/b4fpc even with g++ -O6
  • matiu
    matiu over 12 years
    This one demonstrates how expensive the copy operation can be by copying a 131 KB object: ideone.com/UNKyr