Sign in to follow this  

Which one to choose vectorA or vectorA* ??

This topic is 3595 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I sometimes come across with the following declarations of std::vector<> template. vector<A> and vector<A*>. Is there any specific reason (e.g. for performance ) to define the template type with class pointers ?

Share this post


Link to post
Share on other sites
Certainly, for complex objects with a non-trivial copy constructor, it could make quite a difference performance wise. That said, the primary reason isn't usually that the copy constructor is slow, but rather the objects are not intended to be copied, or are not designed such that they can be initialized via a default (parameterless) constructor.

Share this post


Link to post
Share on other sites
Quote:
Original post by nuvem
Certainly, for complex objects with a non-trivial copy constructor, it could make quite a difference performance wise. That said, the primary reason isn't usually that the copy constructor is slow, but rather the objects are not intended to be copied, or are not designed such that they can be initialized via a default (parameterless) constructor.
The Standard C++ Library container classes work perfectly well with classes that are not default-constructable.

In general vector< A * > is a poor choice, simply because of the question of ownership - who owns the objects and is responsible for their deletion? Superior alternatives in this case are constructs like boost::ptr_vector< A > (for vectors which own their contained pointers) and std::vector< boost::shared_ptr< A > > (when ownership and lifetimes are more complicated).

Σnigma

Share this post


Link to post
Share on other sites

This topic is 3595 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this