C++智能指针

来源:互联网 发布:宿迁网络问政12345下载 编辑:程序博客网 时间:2024/06/05 20:20

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

#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