Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deep copy full object behind boost::shared_ptr<T> into shared_ptr pointing to new location?

How to copy full object behind boost::shared_ptr<T>: are there memcopy options (just create memory clone), or we shall create copy constructor?

like image 776
DuckQueen Avatar asked Nov 03 '22 01:11

DuckQueen


2 Answers

You need a copy constructor or an operator= that will perform the deep copy.

boost::shared_ptr cannot know your object's structure to do this for you. Neither can a "memory clone" operation.

Of course, this is only for objects, that need an explicitly defined copy constructor / operator= and the "trivial" ones make a shallow copy.

like image 155
Kiril Kirov Avatar answered Nov 08 '22 06:11

Kiril Kirov


If you know the exact type of the object, then you should use a copy constructor or copy assignment operator.

If the objects is an instance of a class in an inheritance hierarchy, and you do not know the exact type of the object, then you should use a virtual clone function.

like image 42
Johan Råde Avatar answered Nov 08 '22 06:11

Johan Råde