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?
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With