std::make_shared 和 std::shared(new)的区别

分配一个内存 并 新建一个 std::shared_ptr 引用它,有两种方法:

使用 std::make_shared;
使用 std::shared的构造,即 std::shared(new xxx)。
推荐使用 std::make_shared来 分配内存并新建shared指针。但是make_shared无法指定deletor,因此如果分配的是一个数组,那么需要考察make_shared的底层是不是调用的delete[],如果是则安全,如果不是则存在一定的内存泄露可能性

//auto response = std::shared_ptr<Response>(new Response(session, this->config.timeout_content));

auto response = std::make_shared<Response>(session, this->config.timeout_content);
				

错误: 

严重性	代码	说明	项目	文件	行
错误	C2248	“SimpleWeb::ServerBase<SimpleWeb::HTTP>::Response::Response”: 无法访问 private 成员(在“SimpleWeb::ServerBase<SimpleWeb::HTTP>::Response”类中声明)	thriftserver	e:\vs2015\vc\include\memory	907
构造函数是保护或私有时,无法使用 make_shared

错误 C2248 表示编译器试图访问一个被声明为 private 的构造函数。

错误原因如下:

  • 使用 new 直接创建对象时,你可以在类的任何友元或成员函数中这样做,因为这些上下文中有权访问 privateprotected 构造函数。
  • 然而,std::make_shared 需要能够从调用它的上下文中访问构造函数,因为它在内部创建对象。如果构造函数是 privateprotected,并且 std::make_shared 的调用不在允许访问这些构造函数的类或友元的上下文中,那么编译器将报错。

Response 类的构造函数被声明为 private,这意味着不能在类外部使用 std::make_shared 来创建 Response 对象。

当创建的对象没有公有的构造函数时, make_shared 就无法使用了

解决方法:

1. 将构造函数改为 `public`,这样 `std::make_shared` 就可以访问它了。

2. 如果构造函数必须保持 `private`,需要在 `Response` 类内部提供一个静态工厂方法来创建 `shared_ptr`,如下所示:

 class Response {
   private:
       Response(std::shared_ptr<Session> session, long timeout_content);
   public:
       static std::shared_ptr<Response> create(std::shared_ptr<Session> session, long timeout_content) {
           return std::shared_ptr<Response>(new Response(session, timeout_content));
       }
   };

使用这个工厂方法:

 auto response = Response::create(session, this->config.timeout_content);

 https://links.jianshu.com/go?to=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F8147027%2Fhow-do-i-call-stdmake-shared-on-a-class-with-only-protected-or-private-const%3Frq%3D1

3. 如果你不控制 `Response` 类的源代码,你可能需要继续使用原来的方式(new)来创建 `shared_ptr`:

   这种情况下,确保你的代码不会在 `new` 和 `std::shared_ptr` 构造函数之间抛出异常,以避免潜在的内存泄漏。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值