【转】C++ std::tr1::shared_ptr使用
2011-12-12 14:49
513 查看
看《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,如果要预防内存泄露,它就是最佳选择!
运行结果:
construct A!!!
construct B!!!
destruct B!!!
destruct A!!!
转自:/article/2506217.html
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!!!
转自:/article/2506217.html
相关文章推荐
- C++学习 std::tr1::shared_ptr使用的一点体会tr1库介绍
- C++ std::tr1::shared_ptr使用
- C++ std::tr1::shared_ptr使用说明
- C++ std::tr1::shared_ptr使用
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- Effective Modern C++ 条款20 把std::weak_ptr当作类似std::shared_ptr的、可空悬的指针使用
- Effective C++之std::tr1::shared_ptr的使用
- c++中关于智能指针std::tr1::shared_ptr的用法
- c++智能指针《二》 std::tr1::shared_ptr
- C++智能指针:TR1的 shared_ptr 和 weak_ptr 使用介绍
- C++学习 std::tr1::shared_ptr、std::tr1::weak_ptr及std::tr1::enable_shared_from_this
- std::tr1::shared_ptr 使用的一点体会
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- boost::shared_ptr与std::tr1::shared_ptr
- std::auto_ptr和tr1::shared_ptr的用法
- C++ std::tr1::bind使用
- Item 20: 使用std::weak_ptr替换会造成指针悬挂的类std::shared_ptr指针
- [C++] Boost智能指针——boost::shared_ptr(使用及原理分析)
- C++中std::tr1::function和bind 组件的使用 和 以boost::function和boost:bind取代虚函数