Mar*_*arc 17 c++ copy-constructor shared-ptr
我正在尝试复制自定义类的对象Event.我有一个指向我从其分配中获得的对象的共享指针:
std::shared_ptr<Event> e = std::make_shared<Event>();
Run Code Online (Sandbox Code Playgroud)
为了获得e(不仅仅是指针的副本)的真实副本,我尝试过:
std::shared_ptr<Event> o = std::make_shared<Event>(*e);
Run Code Online (Sandbox Code Playgroud)
但我不确定这是否是正确的方式,因为如果我删除e它也会删除o...
顺便说一句,我还没有定义一个拷贝构造函数,Event::Event(const Event &orig)但在我的理解中,这并不是必需的,因为编译器提供了一个默认的拷贝构造函数.事件类只包含变量而没有其他指针.
BЈо*_*вић 11
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 )... ) );
}
Run Code Online (Sandbox Code Playgroud)
在您的特定情况下:
std::shared_ptr<Event> o = std::make_shared<Event>(*e);
Run Code Online (Sandbox Code Playgroud)
对象被复制.
如果您的代码是这样的:
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);
}
Run Code Online (Sandbox Code Playgroud)
当然,当它们超出范围时,两个对象都会被破坏.
如果动态类型*e为Event,而不是从派生的某些类,则您尝试的操作应该可以正常工作Event。(如果*e实际上是从中派生的对象,Event则您将创建一个新的Event(不是派生的类型)作为的基类部分的副本,*e即您将“切片” *e)。
由于您e使用进行创建,因此make_shared<Event>()您知道在这种情况下它确实是一个Event,因此std::make_shared<Event>(*e)应该制作一个shared_ptr拥有的副本的新文件*e。