在C ++中shared_ptr的确切用途是什么? [英] What is the exact use of shared_ptr in c++?

查看:102
本文介绍了在C ++中shared_ptr的确切用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们使用shared_ptr?

Why we use shared_ptr?

<br />
<br />
<pre lang="xml">#include<iostream><br />
#include<memory><br />
#include <vector><br />
<br />
using namespace std;<br />
class x<br />
{<br />
    public:<br />
    int i;<br />
    x():i(12323123)<br />
    {<br />
        cout<<"constructor called"<<endl;<br />
    }<br />
    ~x()<br />
    {<br />
        cout<<"destructor called"<<endl;<br />
    }<br />
};<br />
    vector< shared_ptr<x> > testvec;<br />
<br />
int test()<br />
{<br />
        shared_ptr<x> n(new x);<br />
            testvec.push_back((n));<br />
}<br />
<br />
main()<br />
<br />
{<br />
    test();<br />
    vector< shared_ptr<x> > tests=((testvec));<br />
    cout<<(*(tests.at(0))).i;<br />
}</pre>

推荐答案

它用于消除应用程序中内存泄漏的风险,因为您不需要记得在完成操作后手动删除指针.
It is used to remove the risk of memory leakage in an application, because you don''t need to remember to manually delete the pointer when you a re done with it.


我假设使用了shared_ptr而不是unique_ptr,以便能够从该向量获得对象的副本,并且仍然具有正确的引用计数对于每个对象.

所以对于代码:
I assume shared_ptr is used rather than unique_ptr to be able to have copies of objects from that vector and still have correct reference count for each object.

so for code:
shared_ptr<x> variable = new x;
{
    vector< shared_ptr<x> > arr;
    arr.push_back(x)
}
</x></x>



在方括号变量中的引用计数等于2,否则等于1.



in the brackets variable will have ref count equal to 2, and equal to 1 otherwise.


这篇关于在C ++中shared_ptr的确切用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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