简体   繁体   English

如何深度复制boost :: shared_ptr后面的完整对象 <T> 进入shared_ptr指向新位置?

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

如何复制boost::shared_ptr<T>后面的完整对象:是否有memcopy选项(只是创建内存克隆),或者我们将创建复制构造函数?

You need a copy constructor or an operator= that will perform the deep copy. 您需要一个复制构造函数或operator=来执行深层复制。

boost::shared_ptr cannot know your object's structure to do this for you. boost::shared_ptr无法知道你的对象的结构为你做这件事。 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. 当然,这仅适用于需要明确定义的复制构造函数/ operator=对象,而“平凡”的对象需要进行浅层复制。

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. 如果对象是继承层次结构中的类的实例,并且您不知道对象的确切类型,则应使用虚拟克隆函数。

You should create a copy constructor and write something like: 您应该创建一个复制构造函数并编写如下内容:

ptr.reset(new T);
*ptr  = *(otherObject.ptr);

in order to deep copy the pointer. 为了深度复制指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM