`

Boost智能指针——shared_ptr (转)

 
阅读更多

boost::scoped_ptr虽然简单易用,但它不能共享所有权的特性却大大限制了其使用范围,而boost::shared_ptr可以解决这一局限。顾名思义,boost::shared_ptr是可以共享所有权的智能指针,首先让我们通过一个例子看看它的基本用法:

#include <string>
#include <iostream>
#include <boost/shared_ptr.hpp>

class implementation
{
public:
~implementation() { std::cout <<"destroying implementation\n"; }
void do_something() { std::cout << "did something\n"; }
};

void test()
{
boost::shared_ptr<implementation> sp1(new implementation());
std::cout<<"The Sample now has "<<sp1.use_count()<<" references\n";

boost::shared_ptr<implementation> sp2 = sp1;
std::cout<<"The Sample now has "<<sp2.use_count()<<" references\n";

sp1.reset();
std::cout<<"After Reset sp1. The Sample now has "<<sp2.use_count()<<" references\n";

sp2.reset();
std::cout<<"After Reset sp2.\n";
}

void main()
{
test();
}

该程序的输出结果如下:

The Sample now has 1 references
The Sample now has 2 references
After Reset sp1. The Sample now has 1 references
destroying implementation
After Reset sp2.

 

 

 

#include <string>
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
using namespace boost;
using namespace std;
class implementation
{
public:
~implementation() { cout <<"destroying implementation\n"; }
void do_something() { cout << "did something\n"; }
};

 

void test()
{
/* boost::shared_ptr<implementation> sp1(new implementation());*/
shared_ptr<implementation> sp1;
sp1=make_shared<implementation>();
cout<<"The Sample now has "<<sp1.use_count()<<" references\n";
//
// shared_ptr<implementation> sp2 = sp1;
// cout<<"The Sample now has "<<sp2.use_count()<<" references\n";
//
// sp1.reset();
// cout<<"After Reset sp1. The Sample now has "<<sp2.use_count()<<" references\n";
//
// sp2.reset();
// cout<<"After Reset sp2.\n";
}

 

int main()
{
test();
cout<<"over!";
}

 

 

 

可以看到,boost::shared_ptr指针sp1和sp2同时拥有了implementation对象的访问权限,且当sp1和sp2都释放对该对象的所有权时,其所管理的的对象的内存才被自动释放。在共享对象的访问权限同时,也实现了其内存的自动管理。

boost::shared_ptr的内存管理机制:

boost::shared_ptr的管理机制其实并不复杂,就是对所管理的对象进行了引用计数,当新增一个boost::shared_ptr对该对象进行管理时,就将该对象的引用计数加一;减少一个boost::shared_ptr对该对象进行管理时,就将该对象的引用计数减一,如果该对象的引用计数为0的时候,说明没有任何指针对其管理,才调用delete释放其所占的内存。

上面的那个例子可以的图示如下:

  1. sp1对implementation对象进行管理,其引用计数为1
  2. 增加sp2对implementation对象进行管理,其引用计数增加为2
  3. sp1释放对implementation对象进行管理,其引用计数变为1
  4. sp2释放对implementation对象进行管理,其引用计数变为0,该对象被自动删除

boost::shared_ptr的特点:

和前面介绍的boost::scoped_ptr相比,boost::shared_ptr可以共享对象的所有权,因此其使用范围基本上没有什么限制(还是有一些需要遵循的使用规则,下文中介绍),自然也可以使用在stl的容器中。另外它还是线程安全的,这点在多线程程序中也非常重要。

boost::shared_ptr的使用规则:

boost::shared_ptr并不是绝对安全,下面几条规则能使我们更加安全的使用boost::shared_ptr:

  1. 避免对shared_ptr所管理的对象的直接内存管理操作,以免造成该对象的重释放
  2. shared_ptr并不能对循环引用的对象内存自动管理(这点是其它各种引用计数管理内存方式的通病)。
  3. 不要构造一个临时的shared_ptr作为函数的参数。
    如下列代码则可能导致内存泄漏:
    void test()
    {
    foo(boost::shared_ptr<implementation>(new implementation()),g());
    }
    正确的用法

    void test()
    {
    boost::shared_ptr<implementation> sp (new implementation());
    foo(sp,g());
    }

 

 

 

 

#include "boost/shared_ptr.hpp"
#include <vector>
#include <iostream>
using namespace std;
using namespace boost;
class A
{
public: virtual void sing()=0;
protected: virtual ~A() {};
};
class B : public A
{
public: virtual void sing()
{ std::cout << "Do re mi fa so la\n"; }
};
boost::shared_ptr<A> createA()
{
boost::shared_ptr<A> p(new B()); return p;
}
int main()
{
vector<boost::shared_ptr<A>> container;
for (int i=0;i<10;++i)
{
container.push_back(createA());
}
std::cout << "The choir is gathered: \n";
for (vector<boost::shared_ptr<A>>::iterator it=container.begin();it!=container.end();++it)
{
(*it)->sing();
}
}

 

 

 

 

 

 

 

 

 

 

 

 

shared_ptr是典型的资源获取即初始化技术。不过shared_ptr采用了更复杂一点RAII方式,因为它实现了引用计数。当创建资源的时候将它放入一个shared_ptr, shared_ptr内部记录对这种资源的引用次数为1次。当这个shared_ptr对象离开作用域时,引用次数减1,shared_ptr对象析构时,检查到引用次数为0了,就销毁资源:

{
boost::shared_ptr<int> pInt(new int(14));
assert(pInt.use_count() == 1); // new int(14)这个指针被引用1次
...... // 此处有一系列代码

 

} //pInt离开作用域, 所以new int(14)被引用次数为0. 指针被销毁。防止了

 

  此处及以下assert代码都会判断成功。如果......跳出异常。那么pInt也离开了作用域,指针照常还是被销毁,所以智能指针可以有效防止资源泄露。

 

考虑更多次的引用情况:

 

{

 

boost::shared_ptr<int> pInt2;
assert(pInt2.use_count() == 0); // temp2还没有引用指针

 

{

 

boost::shared_ptr<int> pInt1(new int(14));
assert(pInt1.use_count() == 1); // new int(14)这个指针被引用1次

 

pInt2 = pInt1;
assert(pInt1.use_count() == 2); // new int(14)这个指针被引用2次
assert(pInt2.use_count() == 2);
} //pInt1离开作用域, 所以new int(14)被引用次数-1

 

assert(pInt2.use_count() == 1);
} // pInt2离开作用域,引用次数-1,现在new int(14)被引用0次,所以销毁它

 

不管资源曾经被多少次引用。当它被引用0次时就会销毁。

 

1.3

 

  在shard_ptr使用中经常会发现,一个对象会有两次被析构的情况。其实这种是因为那个对象指针被两次当成shard_ptr构造函数里的参数。一定要避免这种现象。考虑如下代码:

 

{
int* pInt = new int(14);
boost::shared_ptr<int> temp1(pInt);
assert(temp1.use_count() == 1); // 用一个指针初始化temp1,temp1认为pInt只被它拥有。所以这个指针被引用1次

 

boost::shared_ptr<int> temp2(pInt); // 用一个指针初始化temp2,temp2认为pInt只被它拥有。所以这个指针被引用1次
assert(temp2.use_count() == 1);

 

} // temp1,temp2都离开作用域,它们都销毁pInt. pInt被销毁了两次!系统终于崩溃了 -_-

 


正确的做法是将原始指针赋给智能指针后,以后的操作都要针对智能指针了.

 

{
boost::shared_ptr<int> temp1(new int(14)); // 资源获取即初始化
assert(temp1.use_count() == 1);

 

boost::shared_ptr<int> temp2(temp1);
assert(temp2.use_count() == 2);

 

} // temp1,temp2都离开作用域,引用次数变为0,指针被销毁

 

1.4
如果资源的创建销毁不是以new,delete的方式创建销毁怎么办?shared_ptr也可以指定删除器:

 

// FileCloser.h FileCloser删除器  
class FileCloser
{
public:
void operator()(FILE *pf)
{
if (pf)
{
fclose(pf);
}
}
};

 

// 某实现文件
{
boost::shared_ptr<FILE> fp(fopen(pszConfigFile, "r"), FileCloser()); // 指定调用FileCloser函数对象销毁资源
}

 


1.5
  shared_ptr已经被即将到来的标准库技术报告所采纳,将成为tr1中的一员。为了以后更好的移植现有代码到C++新标准中。可以使用一个namespace的一个小技巧,在头文件StdAfx.h中声明(参考

 

Effective C++ Item 54):
namespace std

 

{

 

namespace tr1 = ::boost; // namespace std::tr1 is an alias

 

} // for namespace boost

 

这样就可以用如下方法写代码:

 

std::tr1::shared_ptr<int> pInt(new int(14));

 

 

 

 

 

 

 

 

 

 

 

#include <iostream>
#include <memory>
#include <boost/shared_ptr.hpp>

using namespace boost;
using std::cout;
using std::endl;
using std::auto_ptr;

class A
{
public:
void print()
{
cout<<"hello"<<endl;
}
};

int main()
{
auto_ptr<A> aptr1(new A);
auto_ptr<A> aptr2;

aptr2 = aptr1;
aptr2->print(); //Ok
cout<<"pointer in aptr1 is: "<<aptr1.get()<<endl;
aptr1->print(); //Wrong!

A *a = new A;
shared_ptr<A> sptr1(a);
shared_ptr<A> sptr2(sptr1); //alright
sptr2 = sptr1;
sptr2->print(); //ok
sptr1->print(); //ok

int *b = new int;
shared_ptr<int> sptr3(b);
shared_ptr<int> sptr4(b); //WRONG!!
return 0;
}

 

 

 

 

 

 

 

 

 

 

总结

引用计数智能指针是非常重要的工具。Boost的 shared_ptr 提供了坚固而灵活的解决方案,它已被广泛用于多种环境下。需要在使用者之间共享对象是常见的,而且通常没有办法通知使用者何时删除对象是安全的。shared_ptr 让使用者无需知道也在使用共享对象的其它对象,并让它们无需担心在没有对象引用时的资源释放。这对于Boost的智能指针类而言是最重要的。你会看到Boost.Smart_ptr中还有其它的智能指针,但这一个肯定是你最想要的。通过使用定制删除器,几乎所有资源类型都可以存入 shared_ptr。这使得shared_ptr 成为处理资源管理的通用类,而不仅仅是处理动态分配对象。与裸指针相比,shared_ptr会有一点点额外的空间代价。我还没有发现由于这些代价太大而需要另外寻找一个解决方案的情形。不要去创建你自己的引用计数智能指针类。没有比使用 shared_ptr智能指针更好的了。

在以下情况时使用 shared_ptr

  • 当有多个使用者使用同一个对象,而没有一个明显的拥有者时

  • 当要把指针存入标准库容器时

  • 当要传送对象到库或从库获取对象,而没有明确的所有权时

  • 当管理一些需要特殊清除方式的资源时[9]

    [9] 通过定制删除器的帮助。

 

 

 

 

 

 

 

 

 

 

 


int main()
{
// test();
// cout<<"over!";
{
int* pInt = new int(14);
boost::shared_ptr<int> temp1(pInt);
assert(temp1.use_count() == 1); // 用一个指针初始化temp1,temp1认为pInt只被它拥有。所以这个指针被引用1次

 

boost::shared_ptr<int> temp2(pInt); // 用一个指针初始化temp2,temp2认为pInt只被它拥有。所以这个指针被引用1次
assert(temp2.use_count() == 1);

 

} // temp1,temp2都离开作用域,它们都销毁pInt. pInt被销毁了两次!系统终于崩溃了 -_-

 


}

 

 

分享到:
评论

相关推荐

    C++11 智能指针之shared_ptr代码详解

    C++中的智能指针首先出现在“准”标准库boost中。 随着使用的人越来越多,为了让开发人员更方便、更安全的使用动态内存,C++11也引入了智能指针来管理动态对象。 在新标准中,主要提供了shared_ptr、unique_ptr、...

    浅析Boost智能指针:scoped_ptr shared_ptr weak_ptr

    scoped_ptrboost::scoped_ptr和std::auto_ptr非常类似,是一个简单的智能指针,它能够保证在离开作用域后对象被自动释放。下列代码演示了该指针的基本应用: 代码如下:#include &lt;string&gt;#include &lt;iostream&gt;#...

    详解C++中shared_ptr的使用教程

    shared_ptr是一种智能指针(smart pointer)。shared_ptr的作用有如同指针,但会记录有多少个shared_ptrs共同指向一个对象。 这便是所谓的引用计数(reference counting)。一旦最后一个这样的指针被销毁,也就是...

    c++ shared_ptr智能指针使用注意事项

    shared_ptr在boost中地位相当重要,其行为接近原始指针,但又比指针更加安全,甚至还能提供基本的线程安全保证。它基本上解决了在使用c++开发过程中不可避免的使用指针而遇到的许多问题,常见的毫无疑问是内存泄漏和...

    shared_from_this() in Constructor:直接替换std :: shared_ptr + std :: enable_shared_from_this-开源

    显然,许多人不喜欢标准std :: enable_... boost库也可以这样做,但是它不允许在析构函数中创建shared_ptrs,并且它不提供release()方法来获取所包含指针的所有权。 但是,不利的一面是,它还没有成为线程安全的。

    C++智能指针详解.pdf

    #include &lt;boost/shared_ptr.hpp&gt; class CBase: public boost::enable_shared_from_this&lt;CBase&gt; { public: virtual void f(){}//必须有个虚函数才能向上向下转换。 } typedef boost::shared_ptr&lt;CBase&gt; CBasePtr; ...

    c++11智能指针解析——揭开底层面纱,完整理解智能指针.pdf

    介绍之前先上⼀张别⼈的表格,来源:,这是c++11中的智能指针与boost库中的⽐较,原本boost就是为完善auto_ptr搞得这些,现在 c++11有了,也就不需要再⽤咯。 2.unique_ptr C++11引⼊了许多便捷的功能,其中也包括...

    C++智能指针用法详解

    一、简介  由于 C++ 语言没有自动...包括:std::auto_ptr、boost::scoped_ptr、boost::shared_ptr、boost::scoped_array、boost::shared_array、boost::weak_ptr、boost:: intrusive_ptr。你可能会想,如此多的智能指

    Boost智能指针示例源码

    本代码为C++类库boost实现的示例源码,使用VS2015编译,代码中有相关的注释,如发现有问题,请不吝指教,谢谢!

    C++智能指针实例详解

    本文通过实例详细阐述了C++关于智能指针的概念及用法,有助于读者加深对智能指针的理解。...包括:std::auto_ptr、boost::scoped_ptr、boost::shared_ptr、boost::scoped_array、boost::shared_array、boost::

    C++11 下使用 Boost.Serialization 库实现智能指针的序列化

    C++11 下使用 Boost.Serialization 库实现智能指针的序列化

    C++智能指针(1).pdf

    C++ 中有四种智能指针:auto_pt、unique_ptr、shared_ptr、weak_ptr 其中后三个是 C++11 ⽀持,第⼀个已经被 C++11 弃⽤且被 unique_prt 代替,不推荐使⽤。下⽂将对其逐个说明。 std::auto_ptr 在这个年代讨论 std...

    st_asio_wrapper——一组包装boost.asio的c/s框架(2.3版)

    消息(std::string包装)不再用boost::shared_ptr包装,之前有过度使用智能指针之嫌。效率上,std::string如果支持引用记数,或者编译器支持std::move语义,是没有损失的(因为也不存在内存的拷贝,反而省了智能指针...

    st_asio_wrapper一组包装boost.asio的c/s框架(2.3版)

    消息(std::string包装)不再用boost::shared_ptr包装,之前有过度使用智能指针之嫌。效率上,std::string如果支持引用记数,或者编译器支持std::move语义,是没有损失的(因为也不存在内存的拷贝,反而省了智能指针...

    Linux 内核里的“智能指针”

    现代的C/C++类库一般会提供智能指针来作为内存管理的折中方案,比如STL的auto_ptr,Boost的Smart_ptr库,QT的QPointer家族,甚至是基于C语言构建的GTK+也通过引用计数来实现类似的功能。Linux内核是如何解决这个问题...

    Boost 程序库完全开发指南

    boost 是 C++ 所谓的“准标准库”,是 C++ 标准库的实验场,其所提供的智能指针 shared_ptr 已经被收入 C++ 的新标准。boost 包含大量设计精巧、功能强大、性能卓越的组件,如智能指针、函数对象、lambda表达式、...

    当析构函数遇到多线程── C++ 中线程安全的对象回调 PDF

    如何避免这种竞态条件是 C++ 多线程编程面临的基本问题,可以借助 boost 的 shared_ptr 和 weak_ptr 完美解决。这也是实现线程安全的 Observer 模式的必备技术。 本文源自陈硕在 2009 年 12 月上海 C++ 技术大会的一...

    当析构函数遇到多线程── C++ 中线程安全的对象回调

    如何避免这种竞态条件是 C++ 多线程编程面临的基本问题,可以借助 boost 的 shared_ptr 和 weak_ptr 完美解决。这也是实现线程安全的 Observer 模式的必备技术。 本文源自我在 2009 年 12 月上海 C++ 技术大会的一场...

Global site tag (gtag.js) - Google Analytics