C++智能指针

代码后面有说明,这里不啰嗦了。

#include "stdafx.h"
#include <memory>
#include <string>
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
    using namespace std;
   /*auto_ptr:会转让所有权,运行时崩溃********/
    auto_ptr<string> films[5] =
    {
        auto_ptr<string> (new string("A")),
        auto_ptr<string> (new string("B")),
        auto_ptr<string> (new string("C")),
        auto_ptr<string> (new string("D")),
        auto_ptr<string> (new string("E"))
    };
    auto_ptr<string> pwin;
    pwin = films[2];//Films[2]失去了对这个元素的所有权,后面的那句打印会出错的。
    //cout << *films[2] << endl;//这句会出错,运行时出错
    cout << *pwin << endl;

    /*unique_ptr:会转让所有权, 编译不过,及运行时崩溃********/
    unique_ptr<string> films02[5] =
    {
        unique_ptr<string> (new string("A")),
        unique_ptr<string> (new string("B")),
        unique_ptr<string> (new string("C")),
        unique_ptr<string> (new string("D")),
        unique_ptr<string> (new string("E"))
    };
    unique_ptr<string> pwin02;
    //pwin = films[2];//Films[2]失去了对这个元素的所有权,编译不过,如果unique_ptr右边是临时变量,可以赋值。
    pwin02 = move(films02[2]);//把所有权转让,用move是可以的。
    cout << *pwin02 << endl;
    //cout << *films02[2] << endl;//这个会运行时错误
    
    /**shared_ptr:引用计数********************/
    shared_ptr<string> films03[5] =
    {
        shared_ptr<string> (new string("A")),
        shared_ptr<string> (new string("B")),
        shared_ptr<string> (new string("C")),
        shared_ptr<string> (new string("D")),
        shared_ptr<string> (new string("E"))
    };
    shared_ptr<string> pwin03;
    pwin03 = films03[2];//films[2]中的引用对像加1
    for (int i = 0; i < 5; ++i)
    {
        cout << *films03[i] << endl;//
    }
    //释放的时候,会依次把对象的引用递减,减到O了就释放对象
    system("pause");
	return 0;
    /*总结:unique_ptr比<span style="font-size: 1em; line-height: 1.5;">auto_ptr更安全,推荐用。</span><span style="font-size: 1em; line-height: 1.5;">在使用容器时,这个要非常小心,特别是容器带有复制的,选择shshared_ptr用比较好一点*/</span>

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值