/* auto_ptr是智能指引,可以自我销毁而不像new出来的对象一样需要调用delete销毁。 auto_ptr赋值用引起所有权的交接,作为函数参数或返回值都会引起所有权的交接。 auto_ptr必须显示初始化 auto_ptr<int> p(new int(43)) //ok auto_ptr<int> p = new int(43) //error auto_ptr<int> p; p = new int(43); //error p = auto_ptr<int>(43) //ok auto_ptr的函数: Type* release() throw(); //将该auto_ptr设为null,并且返回该对象的地址 void reset(TYPE *_ptr = 0); //用来接收所有权,如果接收所有权者已经拥有了对象,则必须先释放该对象。其中_ptr是TYPE类型的指针,它将会替换原来auto_ptr所拥有的指针。 TYPE* get() const throw; //返回该类存储的指针。 */ #include <memory> #include <iostream> using namespace std; class Int { public: Int( int i ) { x = i; cout << "Constructing " << ( void* )this << " Value: " << x << endl; }; ~Int( ) { cout << "Destructing " << ( void* )this << " Value: " << x << endl; }; int x; }; int main( ) { auto_ptr<Int> pi ( new Int( 5 ) ); pi.reset( new Int( 6 ) ); Int* pi2 = pi.get ( ); Int* pi3 = pi.release ( ); cout<<pi.get()<<endl; if ( pi2 == pi3 ) cout << "pi2 == pi3" << endl; delete pi3; } /* Constructing 0x3e2be8 Value: 5 Constructing 0x3e4af8 Value: 6 Destructing 0x3e2be8 Value: 5 //一个auto_ptr只能指向一个对象,所以在赋新值前先要销毁旧的。 0 //调用release()后auto_ptr返回其存储值,并赋空, pi2 == pi3 //pi2与pi3都是原来pi存储类的指针。 Destructing 0x3e4af8 Value: 6 */
Date: 2011-11-24 16:21:36
HTML generated by org-mode 6.33x in emacs 23
原文链接: https://www.cnblogs.com/visayafan/archive/2011/11/24/2261921.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/37161
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!