智能指针模板

最近在面试中经常问到关于C++11新标准,在这里简单的总结一下智能指针模板,方便记忆。

1.智能指针模板 (在头文件<memory>中)前提是编译器支持C++11标准

<1>首先就是智能指针auto_ptr、shared_ptr、unique_ptr,这三个指针模板的特点相比传统的指针来说,不需要在使用之后进行显式的内存释放工作,当它们过期时,相应的析构函数将使用delete来释放它们所申请的内存地址空间。

因此在由常规指针转换成智能指针模板时,一般需要三个步骤:

1.包含头文件<memory>

2.将指向类型T的指针转变为指向T的智能指针对象,如

std::string str="Hello,World!";
std::string *ps=new std::string(str);
/*******************************************/
std::auto_ptr<std::string>ps(new std::string(str));
std::string temp=*ps;

 3.删除delete语句。

注意:所有智能指针都一个explicit构造函数,该构造函数将指针作为参数,因此不需要自动将指针转换为智能指针对象:

shared_ptr<double>pd;
double *p=new double;
pd=p;//not allow(implicit conversion)
pd=shared_ptr<double>(p);//allow(explicit conversion)
shared_ptr<double>ps=p;//not allow(implicit conversion)
shared_ptr<double>ps(p)allow(explicit conversion)

//alert the follow point
string vaca("Tsinghua");
shared_ptr<double>pp(&vaca)//not allow
/*pp过期时,程序将把delete用于非heap内存*/

<2>下面我们来看一下auto_ptr、shared_ptr和unique_ptr的区别

首先来看一个例子:

auto_ptr<string>p1(new string("I love spring"));
auto_ptr<string>p2;
p2=p1;

如果p1和p2是常规指针那么,将会出现两个指针指向同一string对象情况,这在C++中显然是不允许的。解决办法就是创建智能更高的指针,当赋值时,计数加1,当指针过期时计数减1.仅当最后一个指针过期时,才调用delete,这正是shared_ptr所采用的策略(功能如名字)。因此程序中auto_ptr换成shared_ptr将会成立。unique_ptr与auto_ptr一样也采用的所有权模型。

但是unique_ptr与auto_ptr的区别呢?

当然,unique_ptr比auto_ptr更安全,因为当出现上面情况时,unique_ptr的编译器将会报错(编译阶段的错误比潜在的程序崩溃更安全),但是unique_ptr允许临时的右值实行下面的赋值:

//#way1
unique_ptr<string> demo(const char *s)
{
     unique_ptr<string> temp(new string(s));
     return temp;
}

//#way2
unique_ptr<string>p;
p=unique_ptr<string>(new string ("unique_ptr"));

实际上unique_ptr可以利用move函数从一个unique_ptr对象到另一个对象,这就用到了移动构造函数和右值引用了。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值