问关于auto_ptr::reset的问题ENauto_ptr管理一个指针。reset将删除它拥有的指针,并指向其他对象。
// auto_ptr_reset.cpp // compile with: /EHsc #include <memory> #include <iostream> #include <vector> using namespace std; class Int { public: Int( int i ) { x = i; cout << "Constructing " << ( void* )this << " Value: " << x << endl; }; ~Int( ) { cout << "Des...
//and pointer becomes NULL p1.reset(); cout << p1.get() << endl; cout << p2.use_count() << endl; cout << p2.get() << endl; return 0; } Output: 0x1c41c20 A::show() A::show() 0x1c41c20 0x1c41c20 2 2 0 // NULL 1 0x1c41c20 何时使用shared_ptr? 如果要共享...
用法一: std::auto_ptr<MyClass>m_example(new MyClass()); 用法二: std::auto_ptr<MyClass>m_example; m_example.reset(new MyClass()); 用法三(指针的赋值操作): std::auto_ptr<MyClass>m_example1(new MyClass()); std::auto_ptr<MyClass>m_example2(new MyClass()); m_example2=m_examp...
等号运算符,先将右操作数释放所有权,然后调用重置Reset方法 另外一种等号运算符,将另外一种类型的指针赋值给当前类型的智能指针,所以参数是_Other 拷贝构造函数,所以参数是_Other 重载了一个类型转换运算符,可以将A类型的智能指针转换为B类型的智能指针(看下面的eg),将某种类型的智能指针转换为其他类型的智能指针 ...
std::auto_ptr的基本用法:#include<memory> int main(){ //初始化方式一 std::auto_ptr<int>sp1( new int(8) ); //初始化方式二 std::auto_ptr<int>sp2; sp2.reset( new int(8) ); return 0;} 在以上代码中,智能指针sp1和sp2均持有一个在堆上分配的int对象,值都为8,这两块...
注:reset(0)可以释放对象,销毁内存。 3) release() 返回auto_ptr指向的那个对象的内存地址,并释放对这个对象的所有权。 用此函数初始化auto_ptr时可以避免两个auto_ptr对象拥有同一个对象的情况(与get函数相比)。 例子如下: auto_ptr< string > pstr_auto( new string( "Brontosaurus" ) ); ...
reset(rhs.release());return*this; } template<classY>auto_ptr&operator=(auto_ptr<Y> &rhs)throw() { reset(rhs.release());return*this; }//Dereference...(3)T&operator*()constthrow() {return*ap; } T* operateor->()constthrow() {returnap...
pNum.reset(pNum->get()); // 不会发送任何事情,安全 4)release 函数释放所有权,返回它管理的指针,不删除指针指向的对象: auto_ptr<int> pNum2(pNum1.release()); // 等同于下句 auto_ptr<int> pNum2(pNum1); // 等同于上句 6. 编译器的问题 ...
智能指针被重置:当auto_ptr被重置(例如使用reset方法)为指向nullptr或另一个对象时,原有的对象会被删除,此时再对原auto_ptr进行解引用就会导致此错误。 cpp auto_ptr<int> p1(new int(10)); p1.reset(new int(20)); // p1现在指向新的对象,原来的对象被删除 cout << *p1 <<...