将shared_ptr自动释放内存吗? [英] Will a shared_ptr automatically free up memory?

查看:403
本文介绍了将shared_ptr自动释放内存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在这里使用shared_ptr,因为我无法更改API。

I need to use a shared_ptr here because I can't change the API.

Foo1 *foo1 = new Foo1(...);
shared_ptr<Foo2> foo2(foo1);

shared_ptr是否会释放foo1使用的内存?如果我理解正确,我不应该调用foo1上的delete正确吗?

Is the shared_ptr here going to handle freeing the memory used by foo1? If I understand correctly, I shouldn't have to call delete on foo1 correct?

推荐答案

您是正确的,但是初始化 foo2 的正确方法是:

Yes. You are correct, but the correct way to initialise foo2 is:

std::shared_ptr<Foo2> foo2 = std::make_shared<Foo1>();  

Herb Sutter讨论了您应该使用 std :: make_shared< ;()此处:
http://herbsutter.com/gotw/_103/

Herb Sutter discusses the reasons why you should use std::make_shared<>() here: http://herbsutter.com/gotw/_103/

这篇关于将shared_ptr自动释放内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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