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 vector cannot keep a reference or a pointer of an object without a copy ?!
Thanks
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 vector cannot keep a reference or a pointer of an object without a copy ?!
Thanks
Yes, std::vector
stores copies. How should vector
know what the expected life-times of your objects are?
If you want to transfer or share ownership of the objects use pointers, possibly smart pointers like shared_ptr
(found in Boost or TR1) to ease resource management.
std::vector always makes a copy of whatever is being stored in the vector.
If you are keeping a vector of pointers, then it will make a copy of the pointer, but not the instance being to which the pointer is pointing. If you are dealing with large objects, you can (and probably should) always use a vector of pointers. Often, using a vector of smart pointers of an appropriate type is good for safety purposes, since handling object lifetime and memory management can be tricky otherwise.
Yes, std::vector<T>::push_back()
creates a copy of the argument and stores it in the vector. If you want to store pointers to objects in your vector, create a std::vector<whatever*>
instead of std::vector<whatever>
.
However, you need to make sure that the objects referenced by the pointers remain valid while the vector holds a reference to them (smart pointers utilizing the RAII idiom solve the problem).
Not only does std::vector make a copy of whatever you're pushing back, but the definition of the collection states that it will do so, and that you may not use objects without the correct copy semantics within a vector. So, for example, you do not use auto_ptr in a vector.
if you want not the copies; then the best way is to use a pointer vector(or another structure that serves for the same goal). if you want the copies; use directly push_back(). you dont have any other choice.