您的位置:首页 > 运维架构

Boost智能指针——scoped_ptr、shared_ptr、weak_ptr、intrusive_ptr

2013-04-23 15:49 696 查看

一、scoped_ptr

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

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

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

void test()
{
boost::scoped_ptr<implementation> impl(new implementation());
impl->do_something();
}

void main()
{
std::cout<<"Test Begin ... \n";
test();
std::cout<<"Test End.\n";
}


该代码的输出结果是:

Test Begin ...

did something

destroying implementation

Test End.
可以看到:当implementation类离其开impl作用域的时候,会被自动删除,这样就会避免由于忘记手动调用delete而造成内存泄漏了。

boost::scoped_ptr特点:

boost::scoped_ptr的实现和std::auto_ptr非常类似,都是利用了一个栈上的对象去管理一个堆上的对象,从而使得堆上的对象随着栈上的对象销毁时自动删除。不同的是,boost::scoped_ptr有着更严格的使用限制——不能拷贝。这就意味着:boost::scoped_ptr指针是不能转换其所有权的。

不能转换所有权

boost::scoped_ptr所管理的对象生命周期仅仅局限于一个区间(该指针所在的"{}"之间),无法传到区间之外,这就意味着boost::scoped_ptr对象是不能作为函数的返回值的(std::auto_ptr可以)。

不能共享所有权

这点和std::auto_ptr类似。这个特点一方面使得该指针简单易用。另一方面也造成了功能的薄弱——不能用于stl的容器中。

不能用于管理数组对象

由于boost::scoped_ptr是通过delete来删除所管理对象的,而数组对象必须通过deletep[]来删除,因此boost::scoped_ptr是不能管理数组对象的,如果要管理数组对象需要使用boost::scoped_array类。

boost::scoped_ptr的常用操作:

可以简化为如下形式:

namespace boost {

template<typename T> class scoped_ptr : noncopyable {
public:
explicit scoped_ptr(T* p = 0);
~scoped_ptr();

void reset(T* p = 0);

T& operator*() const;
T* operator->() const;
T* get() const;

void swap(scoped_ptr& b);
};

template<typename T>
void swap(scoped_ptr<T> & a, scoped_ptr<T> & b);
}


它的常用操作如下:

成员函数
功能
operator*()
以引用的形式访问所管理的对象的成员
operator->()
以指针的形式访问所管理的对象的成员
get()
释放所管理的对象,管理另外一个对象
swap(scoped_ptr& b)
交换两个boost::scoped_ptr管理的对象
下列测试代码演示了这些功能函数的基本使用方法。

#include <string>
#include <iostream>

#include <boost/scoped_ptr.hpp>
#include <boost/scoped_array.hpp>

#include <boost/config.hpp>
#include <boost/detail/lightweight_test.hpp>

void test()
{
// test scoped_ptr with a built-in type
long * lp = new long;
boost::scoped_ptr<long> sp ( lp );
BOOST_TEST( sp.get() == lp );
BOOST_TEST( lp == sp.get() );
BOOST_TEST( &*sp == lp );

*sp = 1234568901L;
BOOST_TEST( *sp == 1234568901L );
BOOST_TEST( *lp == 1234568901L );

long * lp2 = new long;
boost::scoped_ptr<long> sp2 ( lp2 );

sp.swap(sp2);
BOOST_TEST( sp.get() == lp2 );
BOOST_TEST( sp2.get() == lp );

sp.reset(NULL);
BOOST_TEST( sp.get() == NULL );

}

void main()
{
test();
}


boost::scoped_ptr和std::auto_ptr的选取:

boost::scoped_ptr和std::auto_ptr的功能和操作都非常类似,如何在他们之间选取取决于是否需要转移所管理的对象的所有权(如是否需要作为函数的返回值)。如果没有这个需要的话,大可以使用boost::scoped_ptr,让编译器来进行更严格的检查,来发现一些不正确的赋值操作。

【转自:http://www.cnblogs.com/TianFang/archive/2008/09/15/1291050.html】

二、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.

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

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

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

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

sp1对implementation对象进行管理,其引用计数为1

增加sp2对implementation对象进行管理,其引用计数增加为2

sp1释放对implementation对象进行管理,其引用计数变为1

sp2释放对implementation对象进行管理,其引用计数变为0,该对象被自动删除

boost::shared_ptr的特点:

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

boost::shared_ptr的使用规则:

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

避免对shared_ptr所管理的对象的直接内存管理操作,以免造成该对象的重释放

shared_ptr并不能对循环引用的对象内存自动管理(这点是其它各种引用计数管理内存方式的通病)。

不要构造一个临时的shared_ptr作为函数的参数。

如下列代码则可能导致内存泄漏:
void test()
{
foo(boost::shared_ptr<implementation>(new    implementation()),g());
}
正确的用法为:
void test()
{
boost::shared_ptr<implementation> sp    (new implementation());
foo(sp,g());
}
ps: (#3) why?
网上看到一个解释:
void fun(AClass b,const shared_ptr<A>& a);

如果使用临时的shared_ptr作为函数的参数

AClass b;

fun(b,shared_ptr<A>(new A()));

如果b的拷贝复制函数操作发送了异常,后面的临时智能指针的引用计数可能无法正确清0来释放内存,造成内存泄漏,正确要写出

shared_ptr<A> aptr(new A());

AClass b;

fun(b,aptr);

三、Boost智能指针——weak_ptr

循环引用:

引用计数是一种便利的内存管理机制,但它有一个很大的缺点,那就是不能管理循环引用的对象。一个简单的例子如下:

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

class parent;
class children;

typedef boost::shared_ptr<parent> parent_ptr;
typedef boost::shared_ptr<children> children_ptr;

class parent
{
public:
~parent() { std::cout <<"destroying parent\n"; }

public:
children_ptr children;
};

class children
{
public:
~children() { std::cout <<"destroying children\n"; }

public:
parent_ptr parent;
};

void test()
{
parent_ptr father(new parent());
children_ptr son(new children);

father->children = son;
son->parent = father;
}

void main()
{
std::cout<<"begin test...\n";
test();
std::cout<<"end test.\n";
}


运行该程序可以看到,即使退出了test函数后,由于parent和children对象互相引用,它们的引用计数都是1,不能自动释放,并且此时这两个对象再无法访问到。这就引起了c++中那臭名昭著的内存泄漏。

一般来讲,解除这种循环引用有下面有三种可行的方法:

当只剩下最后一个引用的时候需要手动打破循环引用释放对象。

当parent的生存期超过children的生存期的时候,children改为使用一个普通指针指向parent。

使用弱引用的智能指针打破这种循环引用。

虽然这三种方法都可行,但方法1和方法2都需要程序员手动控制,麻烦且容易出错。这里主要介绍一下第三种方法和boost中的弱引用的智能指针boost::weak_ptr。

强引用和弱引用

一个强引用当被引用的对象活着的话,这个引用也存在(就是说,当至少有一个强引用,那么这个对象就不能被释放)。boost::share_ptr就是强引用。

相对而言,弱引用当引用的对象活着的时候不一定存在。仅仅是当它存在的时候的一个引用。弱引用并不修改该对象的引用计数,这意味这弱引用它并不对对象的内存进行管理,在功能上类似于普通指针,然而一个比较大的区别是,弱引用能检测到所管理的对象是否已经被释放,从而避免访问非法内存。

boost::weak_ptr

boost::weak_ptr<T>是boost提供的一个弱引用的智能指针,它的声明可以简化如下:

namespace boost {

template<typename T> class weak_ptr {
public:
template <typename Y>
weak_ptr(const shared_ptr<Y>& r);

weak_ptr(const weak_ptr& r);

~weak_ptr();

T* get() const;
bool expired() const;
shared_ptr<T> lock() const;
};
}


可以看到,boost::weak_ptr必须从一个boost::share_ptr或另一个boost::weak_ptr转换而来,这也说明,进行该对象的内存管理的是那个强引用的boost::share_ptr。boost::weak_ptr只是提供了对管理对象的一个访问手段。

boost::weak_ptr除了对所管理对象的基本访问功能(通过get()函数)外,还有两个常用的功能函数:expired()用于检测所管理的对象是否已经释放;lock()用于获取所管理的对象的强引用指针。

通过boost::weak_ptr来打破循环引用

由于弱引用不更改引用计数,类似普通指针,只要把循环引用的一方使用弱引用,即可解除循环引用。对于上面的那个例子来说,只要把children的定义改为如下方式,即可解除循环引用:

class children
{
public:
~children() { std::cout <<"destroying children\n"; }

public:
boost::weak_ptr<parent> parent;
};


最后值得一提的是,虽然通过弱引用指针可以有效的解除循环引用,但这种方式必须在程序员能预见会出现循环引用的情况下才能使用,也可以是说这个仅仅是一种编译期的解决方案,如果程序在运行过程中出现了循环引用,还是会造成内存泄漏的。因此,不要认为只要使用了智能指针便能杜绝内存泄漏。毕竟,对于C++来说,由于没有垃圾回收机制,内存泄漏对每一个程序员来说都是一个非常头痛的问题。

四、智能指针——boost::intrusive_ptr

boost::intrusive_ptr一种“侵入式”的引用计数指针,它实际并不提供引用计数功能,而是要求被存储的对象自己实现引用计数功能,并提供intrusive_ptr_add_ref和intrusive_ptr_release函数接口供boost::intrusive_ptr调用。

下面通过一个具体的例子来说明boost::intrusive_ptr的用法,首先实现一个基类intrusive_ptr_base,定义intrusive_ptr_add_ref和intrusive_ptr_release函数来提供引用计数功能。

/**
* intrusive_ptr_base基类,提供intrusive_ptr_add_ref()和intrusive_ptr_release()函数来提供引用计数功能;
* 使用boost::intrusive_ptr指针存储的用户类类型必须继承自intrusive_ptr_base基类。
*/
#include <ostream>
#include <boost/checked_delete.hpp>
#include <boost/detail/atomic_count.hpp>

template<class T>
class intrusive_ptr_base {
public:
/**
* 缺省构造函数
*/
intrusive_ptr_base(): ref_count(0) {
std::cout << "  Default constructor " << std::endl;
}

/**
* 不允许拷贝构造,只能使用intrusive_ptr来构造另一个intrusive_ptr
*/
intrusive_ptr_base(intrusive_ptr_base<T> const&): ref_count(0) {
std::cout << "  Copy constructor..." << std::endl;
}

/**
* 不允许进行赋值操作
*/
intrusive_ptr_base& operator=(intrusive_ptr_base const& rhs) {
std::cout << "  Assignment operator..." << std::endl;
return *this;
}

/**
* 递增引用计数(放到基类中以便compiler能找到,否则需要放到boost名字空间中)
*/
friend void intrusive_ptr_add_ref(intrusive_ptr_base<T> const* s) {
std::cout << "  intrusive_ptr_add_ref..." << std::endl;
assert(s->ref_count >= 0);
assert(s != 0);
++s->ref_count;
}

/**
* 递减引用计数
*/
friend void intrusive_ptr_release(intrusive_ptr_base<T> const* s) {
std::cout << "  intrusive_ptr_release..." << std::endl;
assert(s->ref_count > 0);
assert(s != 0);
if (--s->ref_count == 0)
boost::checked_delete(static_cast<T const*>(s));  //s的实际类型就是T,intrusive_ptr_base<T>为基类
}

/**
* 类似于shared_from_this()函数
*/
boost::intrusive_ptr<T> self() {
return boost::intrusive_ptr<T>((T*)this);
}

boost::intrusive_ptr<const T> self() const {
return boost::intrusive_ptr<const T>((T const*)this);
}

int refcount() const {
return ref_count;
}

private:
///should be modifiable even from const intrusive_ptr objects
mutable boost::detail::atomic_count ref_count;

};


用户类类型需要继承intrusive_ptr_base基类,以便具有引用计数功能。

#include <iostream>
#include <string>
#include <boost/intrusive_ptr.hpp>
#include "intrusive_ptr_base.hpp"

/**
* 用户类类型继承自intrusive_ptr_base,该实现方式类似于boost::enable_shared_from_this<Y>
*/
class Connection : public intrusive_ptr_base< Connection > {
public:
/**
* 构造函数,调用intrusive_ptr_base< Connection >的缺省构造函数来初始化对象的基类部分
*/
Connection(int id, std::string tag):
connection_id( id ), connection_tag( tag ) {}

/**
* 拷贝构造函数,只复制自身数据,不能复制引用计数部分
*/
Connection(const Connection& rhs):
connection_id( rhs.connection_id ), connection_tag( rhs.connection_tag) {}

/**
* 赋值操作,同样不能复制引用计数部分
*/
const Connection operator=( const Connection& rhs) {
if (this != &rhs) {
connection_id = rhs.connection_id;
connection_tag = rhs.connection_tag;
}

return *this;
}

private:
int connection_id;
std::string connection_tag;
};

int main() {
std::cout << "Create an intrusive ptr" << std::endl;
boost::intrusive_ptr< Connection > con0 (new Connection(4, "sss") );  //调用intrusive_ptr_add_ref()递增引用计数
std::cout << "Create an intrusive ptr. Refcount = " << con0->refcount() << std::endl;

boost::intrusive_ptr< Connection > con1 (con0);   //调用intrusive_ptr_add_ref()
std::cout << "Create an intrusive ptr. Refcount = " << con1->refcount() << std::endl;
boost::intrusive_ptr< Connection > con2 = con0;   //调用intrusive_ptr_add_ref()
std::cout << "Create an intrusive ptr. Refcount = " << con2->refcount() << std::endl;

std::cout << "Destroy an intrusive ptr" << std::endl;

return 0;
}


程序运行输出:

Create an intrusive ptr

Default constructor

intrusive_ptr_add_ref...

Create an intrusive ptr. Refcount = 1

intrusive_ptr_add_ref...

Create an intrusive ptr. Refcount = 2

intrusive_ptr_add_ref...

Create an intrusive ptr. Refcount = 3

Destroy an intrusive ptr

intrusive_ptr_release...

intrusive_ptr_release...

intrusive_ptr_release...

对比boost::shared_ptr

使用boost::shared_ptr用户类本省不需要具有引用计数功能,而是由boost::shared_ptr来提供;使用boost::shared_ptr的一大陷阱就是用一个raw pointer多次创建boost::shared_ptr,这将导致该raw pointer被多次销毁当boost::shared_ptr析构时。即不能如下使用:

int *a = new int(5);

boost::shared_ptr ptr1(a);

boost::shared_ptr ptr2(a);  //错误!

boost::intrusive_ptr完全具备boost::shared_ptr的功能,且不存在shared_ptr的问题,即可以利用raw pointer创建多个intrusive _ptr,其原因就在于引用计数的ref_count对象,shared_ptr是放在shared_ptr结构里,而目标对象T通过继承intrusive_ptr_base将引用计数作为T对象的内部成员变量,就不会出现同一个对象有两个引用计数器的情况出现。

那么为什么通常鼓励大家使用shared_ptr,而不是intrusive_ptr呢, 在于shared_ptr不是侵入性的,可以指向任意类型的对象; 而intrusive_ptr所要指向的对象,需要继承intrusive_ptr_base,即使不需要,引用计数成员也会被创建。

结论:如果创建新类且需要进行传递,则继承intrusive_ptr_base,使用intrusive_ptr。

【(四)转自:http://www.cnblogs.com/edwardlost/archive/2011/02/17/1957019.html】
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐