初始化shared_ptr成员变量,new vs make_shared? [英] Initializing shared_ptr member variable, new vs make_shared?

查看:904
本文介绍了初始化shared_ptr成员变量,new vs make_shared?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

初始化shared_ptr成员变量时:

When initializing a shared_ptr member variable:

// .h
class Customer
{
public:
  Customer();

private:
  std::shared_ptr<OtherClass> something_;
}

// .cpp
Customer():
  something_(new OtherClass())
{
}

vs。

Customer():
  something_(std::make_shared<OtherClass>())
{
}

是否允许make_shared版本?

Is the make_shared version allowed? I always seem to see the first version, which is preferred?

推荐答案

只有当 make_shared 是不允许的:

The only times when make_shared is not allowed are:


  1. 如果你得到一个裸指针并将其存储在 shared_ptr 中。

  2. 如果要调用的构造函数不是public的( make_shared 只能调用公共建设者)。这可能发生在工厂函数中,您希望强制用户从工厂创建对象。但你可以通过使 make_shared 的特定实例成为朋友来解决这个问题。

  1. If you're getting a naked pointer allocated by someone else and storing it in shared_ptr. This is often the case when interfacing with C APIs.
  2. If the constructor you want to call is not public (make_shared can only call public constructors). This can happen with factory functions, where you want to force users to create the object from the factory. But you may be able to get around this by making the particular instance of make_shared a friend.

是的,你可以这样做。

这篇关于初始化shared_ptr成员变量,new vs make_shared?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆