I'm working on a C++ project and I wonder if it's possible to store the same object in two different vector. I know how to deal with it in C with pointer, so you reference the same object to both table, but I'm little bit confused in C++.
If I create an object and I store it in vector a and in vector b. Do C++ copy the object or it's the same on both vector and if I modify one, the other is modified too ? In the second case, does it take more place to store it twice (for accessibility issues) or it's not a good way to deal with it ?
Thanks.
Cppreference is a great place to check exactly this type of questions. Let me quote the relevant parts of the link:
void push_back( const T& value );
void push_back( T&& value );
Appends the given element value to the end of the container.
1) The new element is initialized as a copy of value.
2) value is moved into the new element.
So yes, storing the same element twice in two vectors will cause it to get copied twice. You should use std::vector<T*> if you don't want to waste memory. And as always, you should also consider smart pointers (std::shared_ptr / std::weak_ptr) instead of naked pointers.
It's similar to C, really.
If what you have is a vector<object>, then you'll be working with different objects.
On the other hand, a vector<object*> ensures that you'll only be storing pointers to your objects and then having multiple vectors containg the same object or objects is not an issue.
You might also consider using std::shared_ptr and std::weak_ptr to simplify memory management when working with pointers in C++.
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