C++ 如何在给定其 shared_ptr 的情况下正确复制对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22782288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:12:50  来源:igfitidea点击:

How to properly duplicate an object given its shared_ptr

c++shared-ptrcopy-constructor

提问by Marc

I'm trying to make a duplicate of an object of a custom class Event. I have a shared pointer to the object that I've obtained from its allocation:

我正在尝试复制自定义类的对象Event。我有一个指向从分配中获得的对象的共享指针:

std::shared_ptr<Event> e = std::make_shared<Event>();

In order to get a true duplicate of e(not just a copy of the pointer) I've tried:

为了获得真正的副本e(不仅仅是指针的副本),我尝试过:

std::shared_ptr<Event> o = std::make_shared<Event>(*e);

But I'm not sure if this is the correct way as it seems that if I delete eit also deletes o...

但我不确定这是否是正确的方法,因为似乎如果我删除e它也会删除o......

Btw, I haven't defined a copy constructor Event::Event(const Event &orig)but in my understanding this is not necessary as the compiler provides a default copy constructor. The event class only contains variables and no further pointers.

顺便说一句,我还没有定义复制构造函数,Event::Event(const Event &orig)但据我所知,这不是必需的,因为编译器提供了默认的复制构造函数。事件类只包含变量,没有进一步的指针。

采纳答案by B?ови?

std::make_sharedis just a simple template function that creates the objects, passing all arguments to the constructor :

std::make_shared只是一个创建对象的简单模板函数,将所有参数传递给构造函数:

template<class T, class... Args>
shared_ptr<T> make_shared(Args&&... args)
{
  return shared_ptr<T>( new T( std::forward<Args>( args )... ) );
}

In your particular case :

在您的特定情况下:

std::shared_ptr<Event> o = std::make_shared<Event>(*e);

the object is copied.

对象被复制。

If your code is such :

如果您的代码是这样的:

void foo() {
    // create new object using default constructor
    std::shared_ptr<Event> e = std::make_shared<Event>();
    // create new object using copy constructor constructor
    std::shared_ptr<Event> o = std::make_shared<Event>(*e);
}

then of course both objects are destroyed, when they go out of scope.

当然,当它们超出范围时,两个对象都会被销毁。

回答by Jonathan Wakely

What you tried should work correctly, ifthe dynamic type of *eis Event, and not some class derived from Event. (If *eis actually an object derived from Eventthen you will create a new Event(not the derived type) as a copy of the base class part of *ei.e. you will "slice" *e).

你试过应该可以正常工作,如果动态类型*eEvent,而不是一些类衍生Event。(如果*e实际上是一个派生的对象,Event那么您将创建一个新的Event(不是派生类型)作为*eie的基类部分的副本,您将“切片” *e)。

Since you create eusing make_shared<Event>()you know that in this case it really is an Event, so std::make_shared<Event>(*e)should make a new shared_ptrthat owns a copy of *e.

由于您e使用创建,make_shared<Event>()您知道在这种情况下它确实是一个Event,因此std::make_shared<Event>(*e)应该创建一个shared_ptr拥有*e.