Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 835
Shai Avatar asked Dec 17 '11 14:12

Shai


3 Answers

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).

like image 100
D.Shawley Avatar answered Oct 16 '22 18:10

D.Shawley


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.

like image 9
iammilind Avatar answered Oct 16 '22 18:10

iammilind


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

like image 3
Alok Save Avatar answered Oct 16 '22 19:10

Alok Save