c++智能指针《二》 std::tr1::shared_ptr

转载http://www.cnblogs.com/kadinzhu/archive/2011/12/12/2284826.html

看《effective c++》,作者一直强调用std::tr1::shared_ptr,比起auto_ptr好多了。

shared_ptr采用引用计数,多个指针可以指向同一个对象;auto_ptr就不能,只能运行一个指针指向一个对象:如果要指针赋值,那么原来的指针要放弃对该对象的所有权。

恩,以后都用shared_ptr。

shared_ptr在最新的c++11中,已经被列入了标准指针,而auto_ptr则出局了。

说了那么多,shared_ptr采用RAII技术,是防止内存泄露的神器。

按bnu_chenshuo的说法,他最后一次看见代码中的内存泄露还是04年他做实习生的时候。

而C++沉思录的作者AndrewKoenig也极力推荐使用标准库,不用指针。

看下面的程序,我new了一个对象,并没有在程序中使用delete,但是,运行程序,其构造函数仍然运行!这就是shared_ptr,如果要预防内存泄露,它就是最佳选择!

# include <iostream>
# include <tr1/memory>
using namespace std;
class A {
public:
    A() {
        cout << "construct A!!!" << endl;
    }
    ;
    ~A() {
        cout << "destruct A!!!" << endl;
    }
    ;
};
class B: public A {
public:
    B() {
        cout << "construct B!!!" << endl;
    }
    ;
    ~B() {
        cout << "destruct B!!!" << endl;
    }
    ;
};
int main() {
//    B* ptrB0 = new B();
    std::tr1::shared_ptr<B> ptrB1(new B);
}

运行结果:

construct A!!!

construct B!!!

destruct B!!!

destruct A!!!

原文地址:https://www.cnblogs.com/ztteng/p/3258120.html