现在的位置: 首页 > 综合 > 正文

c++智能指针

2014年06月12日 ⁄ 综合 ⁄ 共 588字 ⁄ 字号 评论关闭

auto_prt :它是(它所指向对象的拥有者),所以当自身对象被摧毁时候,该对象也将遭受摧毁,要求一个对象只有一个拥有者,

注意:

auto_prt 不能使用new 来分配对象给他

#include <iostream>

#include <memory>

using namespace std;

template <class T>
void bad_print(auto_ptr<T> f){
cout<<*f; 
}

int _tmain(int argc, _TCHAR* argv[])
{
auto_ptr<int> p(new int);
*p = 42;
bad_print(p);  //auot_ptr 指针在作为函数参数专递和函数的返回值的时候,会转让所属权力,就会释放掉当前指的对象
//*p = 50;      
auto_ptr<int> q (new int);
q = p;        //auot_ptr 指针在作为复制和拷贝构造函数值的时候,会转让所属权力
//*p = 50;
return 0;
}

解决上面的办法就是const reference

即是 void bad_print(const auto_ptr<T>& f){ cout<<*f; }

注意:

一个auto_ptr 不要指向另外一个auto_ptr ,因为在赋值的时候,换转染所属权,到时候旧的的对象就会被释放,而新的指针指向一个被释放的对象,

也不要用一个auot_ptr指向一个I额array

抱歉!评论已关闭.