c – shared_ptr的基本语法问题

c – shared_ptr的基本语法问题,第1张

概述我是shared_ptr的新手.我有几个关于C 0x shared_ptr语法的问题如下: //first questionshared_ptr<classA>ptr(new classA()); //worksshared_ptr<classA>ptr;ptr = ?? //how could I create a new object to assign it to shared poi 我是shared_ptr的新手.我有几个关于C 0x shared_ptr语法的问题如下:
//first questionshared_ptr<classA>ptr(new classA()); //worksshared_ptr<classA>ptr;ptr = ?? //how Could I create a new object to assign it to shared pointer?//second questionshared_ptr<classA>ptr2; //Could be tested for NulL from the if statement belowshared_ptr<classA> ptr3(new classA());ptr3 = ?? //how Could I assign NulL again to ptr3 so that the if statement below becomes true?if(!ptr3) cout << "ptr equals null";
解决方法
shared_ptr<classA> ptr;ptr = shared_ptr<classA>(new classA(params));// or:ptr.reset(new classA(params));// or better:ptr = make_shared<classA>(params);ptr3 = shared_ptr<classA>();// orptr3.reset();

编辑:总结一下为什么make_shared比显式调用new更受欢迎:

>某些(所有?)实现对构造的对象和计数器/删除器使用一个内存分配.这提高了性能.
>这是异常安全的,考虑一个函数采用两个shared_ptrs:

f(shared_ptr<A>(new A),shared_ptr<B>(new B));

由于未定义评估顺序,因此可能的评估可以是:构造A,构造B,初始化share_ptr< A>,初始化shared_ptr< B>.如果B抛出,你会泄漏A.>责任分离.如果shared_ptr负责删除,也要对分配负责.

总结

以上是内存溢出为你收集整理的c – shared_ptr的基本语法问题全部内容,希望文章能够帮你解决c – shared_ptr的基本语法问题所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1255647.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存