Boost库有着”C++’准’标准库”之称,内容涵盖字符串处理,正则表达式,容器与数据结构,并发编程,函数式编程,泛型编程,设计模式实现等许多领域,这一篇学习Boost高效的内存管理方法
之前学习过C++11中的智能指针auto_ptr/shared_ptr/unique_ptr ,读者可以回顾一下。实质上,C++新标准的TR1库收录了Boost库中的shared_ptr和weak_ptr
智能指针的作用将申请的空间交由对象管理,不再需要程序员手动delete掉申请的空间,而是交由析构函数在对象过期时析构。
本章主要剖析scoped_ptr,scoped_array,shared_ptr,shared_array,weak_ptr
scoped_ptr
scoped_ptr所有权机制更加严格,不能转让(这是因为它的拷贝构造函数以及赋值函数被声明成私有的)
为了更好理解scoped_ptr
release函数
//代码片1 release函数
//release()设auto_ptr为NULL,返回其内部指针
class auto_ptr_with_deleter
{
public:
explicit auto_ptr_with_deleter(T* p) :
m_p(p)
{}
~auto_ptr_with_deleter(){
if (m_p)
boost::serialization::access::destroy(m_p);
}
T* get() const {
return m_p;
}
T* release() {
T* p = m_p;
m_p = NULL;
return p;
}
private:
T* m_p;
};
checked_delete函数
//代码片2 checked_delete函数
template<class T> inline void checked_delete(T * x)
{
// intentionally complex - simplification causes regressions
typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
(void) sizeof(type_must_be_complete);
delete x;
}
关于type_must_complete的介绍
The checked delete idiom relies on calls to a function template to delete memory, rather than calls to delete, which fails for declared but undefined types.
The following is the implementation of boost::checked_delete, a function template in the Boost Utility library. It forces a compilation error by invoking the sizeof operator on the parameterizing type, T. If T is declared but not defined, sizeof(T) will generate a compilation error or return zero, depending upon the compiler. If sizeof(T) returns zero, checked_delete triggers a compilation error by declaring an array with -1 elements. The array name is type_must_be_complete, which should appear in the error message in that case, helping to explain the mistake.
被检查的删除习语依赖于对功能模板的调用来删除内存,而不是调用delete,对于已声明但未定义的类型而言,该方法失败。
以下是boost :: checked_delete的实现,Boost实用程序库中的函数模板。 它通过调用参数化类型T的sizeof运算符来强制编译错误。如果T声明但未定义,则sizeof(T)将根据编译器生成编译错误或返回零。 如果sizeof(T)返回零,则checked_delete通过声明具有-1个元素的数组来触发编译错误。 数组名称是type_must_be_complete,在这种情况下应该出现在错误消息中,有助于解释错误。
简单点说,就是如果类型未定义,编译时,checked_delete错误信息将出现type_must_be_complete,使得错误更加明了
举个例子
#include <iostream>
using namespace std;
#if TEST
void Test();
template<class T>
inline void checked_delete(T * x)
{
typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
(void) sizeof(type_must_be_complete);
delete x;
}
#else
template<class T>
inline void checked_delete(T * x)
{
delete x;
}
#endif
int main()
{
checked_delete(Test);
}
测试
unspecified_bool_type函数
//代码片3 用来测试scoped_ptr是否持有一个有效的指针(非空),如if(sp){...}
operator unspecified_bool_type() const // never throws
{
return px == 0? 0: unspecified_bool;
}
“scoped_ptr.h”全注释
#ifndef BOOST_SMART_PTR_SCOPED_PTR_HPP_INCLUDED
#define BOOST_SMART_PTR_SCOPED_PTR_HPP_INCLUDED
// (C) Copyright Greg Colvin and Beman Dawes 1998, 1999.
// Copyright (c) 2001, 2002 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// http://www.boost.org/libs/smart_ptr/scoped_ptr.htm
//
#include <boost/assert.hpp>
#include <boost/checked_delete.hpp>
#include <boost/detail/workaround.hpp>
#ifndef BOOST_NO_AUTO_PTR
# include <memory> // for std::auto_ptr
#endif
namespace boost
{
// Debug hooks
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
void sp_scalar_constructor_hook(void * p);
void sp_scalar_destructor_hook(void * p);
#endif
// scoped_ptr mimics a built-in pointer except that it guarantees deletion
// of the object pointed to, either on destruction of the scoped_ptr or via
// an explicit reset(). scoped_ptr is a simple solution for simple needs;
// use shared_ptr or std::auto_ptr if your needs are more complex.
template<class T> class scoped_ptr // noncopyable
{
private:
//原始指针
T * px;
//拷贝构造函数and赋值操作符被声明成私有的,作用:
//不允许将指针所有权移交给其他对象,当然成员函数get()违背了这一点,将原始指针脱离对象的控制。
scoped_ptr(scoped_ptr const &);
scoped_ptr & operator=(scoped_ptr const &);
typedef scoped_ptr<T> this_type;
//等于and不等于声明成私有,作用:
//不允许比较
void operator==( scoped_ptr const& ) const;
void operator!=( scoped_ptr const& ) const;
public:
typedef T element_type;
//不允许隐式转换
explicit scoped_ptr( T * p = 0 ): px( p ) // never throws
{
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
boost::sp_scalar_constructor_hook( px );
#endif
}
#ifndef BOOST_NO_AUTO_PTR
//p.release()设auto_ptr为NULL,返回其内部指针,如代码片1所示
explicit scoped_ptr( std::auto_ptr<T> p ): px( p.release() ) // never throws
{
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
boost::sp_scalar_constructor_hook( px );
#endif
}
#endif
//析构函数,调用checked_delete而不是delete,如代码片2所示详解
~scoped_ptr() // never throws
{
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
boost::sp_scalar_destructor_hook( px );
#endif
boost::checked_delete( px );
}
// this_type是scoped<T>的别名,这里做法很高明
// 将p的所有权交给无名临时对象,使reset总共达到了两个目的:
// (1)将px与p交换,
// (2)reset调用完毕,无名临时对象被释放,即px被释放
void reset(T * p = 0) // never throws
{
BOOST_ASSERT( p == 0 || p != px ); // catch self-reset errors
this_type(p).swap(*this);
}
// 解引用的重载,返回对象
T & operator*() const // never throws
{
BOOST_ASSERT( px != 0 );
return *px;
}
//重载->,返回指针
T * operator->() const // never throws
{
BOOST_ASSERT( px != 0 );
return px;
}
// 返回原始指针,某些场景可以用到(如底层C接口),不过如果对这个指针进行delete操作,scoped_ptr析构时会发生未定义行为(如程序崩溃)
T * get() const // never throws
{
return px;
}
// implicit conversion to "bool"
#include <boost/smart_ptr/detail/operator_bool.hpp>
// 交换两个指针
void swap(scoped_ptr & b) // never throws
{
T * tmp = b.px;
b.px = px;
px = tmp;
}
};
template<class T> inline void swap(scoped_ptr<T> & a, scoped_ptr<T> & b) // never throws
{
a.swap(b);
}
// get_pointer(p) is a generic way to say p.get()
template<class T> inline T * get_pointer(scoped_ptr<T> const & p)
{
return p.get();
}
} // namespace boost
#endif // #ifndef BOOST_SMART_PTR_SCOPED_PTR_HPP_INCLUDED
scoped_ptr与auto_ptr不同的是:auto_ptr可以转让使用权,在转让的时候,上一个指针失去使用权。而scoped_ptr不允许转让使用权。
scoped_ptr和auto_ptr都不能放在容器,auto_ptr是因为它只允许一个auto_prt使用指针,而scoped_ptr是因为不允许转让使用权,不支持拷贝和复制,不符合容器对元素的要求。
scoped_array
scoped_array功能类似scoped_ptr,scoped_array管理的是new[]开辟的数组,其析构函数调用的是delete[]释放数组。
它没有重载解引用*和箭头操作符->,因为它不是普通指针,而是一个数组。它重载了[],可以像使用数组下标那样访问数组。
#ifndef BOOST_SMART_PTR_SCOPED_ARRAY_HPP_INCLUDED
#define BOOST_SMART_PTR_SCOPED_ARRAY_HPP_INCLUDED
// (C) Copyright Greg Colvin and Beman Dawes 1998, 1999.
// Copyright (c) 2001, 2002 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// http://www.boost.org/libs/smart_ptr/scoped_array.htm
//
#include <boost/assert.hpp>
#include <boost/checked_delete.hpp>
#include <boost/config.hpp> // in case ptrdiff_t not in std
#include <boost/detail/workaround.hpp>
#include <cstddef> // for std::ptrdiff_t
namespace boost
{
// Debug hooks
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
void sp_array_constructor_hook(void * p);
void sp_array_destructor_hook(void * p);
#endif
// scoped_array extends scoped_ptr to arrays. Deletion of the array pointed to
// is guaranteed, either on destruction of the scoped_array or via an explicit
// reset(). Use shared_array or std::vector if your needs are more complex.
template<class T> class scoped_array // noncopyable
{
private:
T * px;
scoped_array(scoped_array const &);
scoped_array & operator=(scoped_array const &);
typedef scoped_array<T> this_type;
void operator==( scoped_array const& ) const;
void operator!=( scoped_array const& ) const;
public:
typedef T element_type;
explicit scoped_array( T * p = 0 ) : px( p ) // never throws
{
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
boost::sp_array_constructor_hook( px );
#endif
}
~scoped_array() // never throws
{
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
boost::sp_array_destructor_hook( px );
#endif
boost::checked_array_delete( px );
}
void reset(T * p = 0) // never throws
{
BOOST_ASSERT( p == 0 || p != px ); // catch self-reset errors
this_type(p).swap(*this);
}
//重载[],可以像访问数组一样访问其元素
T & operator[](std::ptrdiff_t i) const // never throws
{
BOOST_ASSERT( px != 0 );
BOOST_ASSERT( i >= 0 );
return px[i];
}
T * get() const // never throws
{
return px;
}
// implicit conversion to "bool"
#include <boost/smart_ptr/detail/operator_bool.hpp>
void swap(scoped_array & b) // never throws
{
T * tmp = b.px;
b.px = px;
px = tmp;
}
};
template<class T> inline void swap(scoped_array<T> & a, scoped_array<T> & b) // never throws
{
a.swap(b);
}
} // namespace boost
#endif // #ifndef BOOST_SMART_PTR_SCOPED_ARRAY_HPP_INCLUDED
但是,scoped_ptr功能有限,需要动态增长,还是建议使用vector