c++ - Is it better to save object pointer in STL container rather than object itself? -


suppose have class a, , need vector of objects class a. better use std::vector<a*> or std::vector<a>? came across lectures mentioned former doesn't require definition of copy constructor , copy assignment operator; while latter requires definitions of both. correct?

the lecture notes not correct: using vector of a uses copy constructor / copy assignment operator, if default implementation provided compiler works you, not required provide own definition.

the decision define copy constructor, assignment operator, , destructor made independently of decision place objects in container. define these three when class allocates resources manually. otherwise, default implementations should work.

back main question, decision store pointer vs. object depends on semantic of collection, , on need store objects polymorphic behavior.

if polymorphic behavior not needed, , creating copies of objects relatively inexpensive, using vector<a> better choice, because lets container manage resources you.

if copying expensive, , need polymorphic behavior, need use pointers. not need raw pointers, though: c++ standard library provides smart pointers deal cleanup you, wouldn't have destroy objects manually.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -