【转】C++ std::tr1::shared_ptr使用
2019-07-14 19:58
190 查看
原文链接:https://www.geek-share.com/detail/2534672540.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,如果要预防内存泄露,它就是最佳选择!
1 # include <iostream>
2 # include <tr1/memory>
3 using namespace std;
4 class A {
5 public:
6 A() {
7 cout << "construct A!!!" << endl;
8 }
9 ;
10 ~A() {
11 cout << "destruct A!!!" << endl;
12 }
13 ;
14 };
15 class B: public A {
16 public:
17 B() {
18 cout << "construct B!!!" << endl;
19 }
20 ;
21 ~B() {
22 cout << "destruct B!!!" << endl;
23 }
24 ;
25 };
26 int main() {
27 // B* ptrB0 = new B();
28 std::tr1::shared_ptr<B> ptrB1(new B);
29 }
运行结果:
construct A!!!
construct B!!!
destruct B!!!
destruct A!!!
转自:https://www.geek-share.com/detail/2525023761.html
转载于:https://www.cnblogs.com/kadinzhu/archive/2011/12/12/2284826.html
相关文章推荐
- C++学习 std::tr1::shared_ptr使用的一点体会tr1库介绍
- C++ std::tr1::shared_ptr使用说明
- 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的用法
- C++学习 std::tr1::shared_ptr、std::tr1::weak_ptr及std::tr1::enable_shared_from_this
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- std::tr1::shared_ptr 使用的一点体会
- c++智能指针《二》 std::tr1::shared_ptr
- Effective C++之std::tr1::shared_ptr的使用
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- Effective Modern C++ 条款20 把std::weak_ptr当作类似std::shared_ptr的、可空悬的指针使用
- C++智能指针:TR1的 shared_ptr 和 weak_ptr 使用介绍
- std::tr1::shared_ptr源码赏析
- c++11 条款19:使用std::shared_ptr来进行共享所有权的资源管理
- C++中std::tr1::function和bind 组件的使用
- [zz]C++中std::tr1::function和bind 组件的使用
- std::tr1::shared_ptr