Shai Shai - 2 months ago 20
C++ Question

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?

Answer

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 baed API methods"; where a copy may not be performed.