C++知识点(16)智能指针shared_ptr的初始化形式

1.默认初始化的智能指针保存着一个空指针NULL

shared_ptr<T> p1;
if(!p1)
	cout<<"p1=NULL"<<endl;

2.一般形式的初始化

  1. 用字符串hello初始化。
shared_ptr<T> p2(new T);
if(p2 && p2->empty())
	cout<<"p1=NULL"<<endl;
  1. 用字符串hello初始化。
shared_ptr<T> p2(new T("hello"));
int *p2_=p2.get();//获取原始指针

3.推荐的安全的初始化方式

shared_ptr<string> p3=make_shared<string>("hello");
shared_ptr<string> p3=make_shared<string>();//初始化空字符串
  1. auto初始化
auto p4=make_shared<string>("hello");
  1. boost shared_ptr
boost::shared_ptr<T> p5=boost::shared_ptr<T>(new T<argc>);

版权声明:本文为lzy6041原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。