Boost源码学习---scoped_ptr.hpp

scoped_ptr是一个智能指针,包装了指向堆上内存的指针。它对指针所有权加以限制,不能转让指针所有权,一旦scoped_ptr获取了指针的管理权,便不再释放,无法再从其取回来,就像scope意思一样,指针智能在作用域使用,不能转让出去。一旦离开scoped_ptr的作用域,将调用它的析构函数,释放指针,不用手动释放。下面是它的源代码:

#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/config.hpp>
#include <boost/assert.hpp>
#include <boost/checked_delete.hpp>
#include <boost/smart_ptr/detail/sp_nullptr_t.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;//原生态指针
		//将复制构造函数和赋值操作符声明为私有,不允许在类外使用,这样就限制了其所有权的转让
    scoped_ptr(scoped_ptr const &);
    scoped_ptr & operator=(scoped_ptr const &);

    typedef scoped_ptr<T> this_type;
		
		//重载为私有,不支持比较
    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

		//参数为auto_ptr时的构造函数
		//p.release()设auto_ptr为NULL,返回其内部指针
    explicit scoped_ptr( std::auto_ptr<T> p ) BOOST_NOEXCEPT : px( p.release() )
    {
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
        boost::sp_scalar_constructor_hook( px );
#endif
    }

#endif
		//析构函数,析构对象,释放内存
    ~scoped_ptr() // never throws
    {
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
        boost::sp_scalar_destructor_hook( px );
#endif
        boost::checked_delete( px );
    }

    void reset(T * p = 0) // never throws
    {
        BOOST_ASSERT( p == 0 || p != px ); // catch self-reset errors
        //把p转换为scoped_prt,再调用swap交换
        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;
    }
		//返回指针
    T * get() const BOOST_NOEXCEPT
    {
        return px;
    }

// implicit conversion to "bool"
#include <boost/smart_ptr/detail/operator_bool.hpp>
		//交换两个指针
    void swap(scoped_ptr & b) BOOST_NOEXCEPT
    {
        T * tmp = b.px;
        b.px = px;
        px = tmp;
    }
};

#if !defined( BOOST_NO_CXX11_NULLPTR )

template<class T> inline bool operator==( scoped_ptr<T> const & p, boost::detail::sp_nullptr_t ) BOOST_NOEXCEPT
{
    return p.get() == 0;
}

template<class T> inline bool operator==( boost::detail::sp_nullptr_t, scoped_ptr<T> const & p ) BOOST_NOEXCEPT
{
    return p.get() == 0;
}

template<class T> inline bool operator!=( scoped_ptr<T> const & p, boost::detail::sp_nullptr_t ) BOOST_NOEXCEPT
{
    return p.get() != 0;
}

template<class T> inline bool operator!=( boost::detail::sp_nullptr_t, scoped_ptr<T> const & p ) BOOST_NOEXCEPT
{
    return p.get() != 0;
}

#endif

template<class T> inline void swap(scoped_ptr<T> & a, scoped_ptr<T> & b) BOOST_NOEXCEPT
{
    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) BOOST_NOEXCEPT
{
    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是因为不允许转让使用权,不支持拷贝和复制,不符合容器对元素的要求。

/work/pcl-cross-compile/src/boost$ ls /work/pcl-cross-compile/install/boost/include/ algorithm dynamic_bitset.hpp make_unique.hpp qvm throw_exception.hpp align enable_shared_from_this.hpp math qvm.hpp timer aligned_storage.hpp exception math_fwd.hpp qvm_lite.hpp timer.hpp align.hpp exception_ptr.hpp move random token_functions.hpp archive foreach_fwd.hpp mpi random.hpp token_iterator.hpp asio foreach.hpp mpi.hpp range tokenizer.hpp asio.hpp format mpl range.hpp tti assign format.hpp multi_array rational.hpp tuple assign.hpp functional multi_array.hpp redis type_erasure call_traits.hpp functional.hpp multi_index redis.hpp type_index cerrno.hpp fusion multi_index_container_fwd.hpp regex type_index.hpp charconv geometry multi_index_container.hpp regex_fwd.hpp typeof charconv.hpp geometry.hpp multiprecision regex.h type_traits circular_buffer gil nondet_random.hpp regex.hpp type_traits.hpp circular_buffer_fwd.hpp gil.hpp none.hpp safe_numerics units circular_buffer.hpp graph none_t.hpp scoped_array.hpp unordered cobalt heap nowide scoped_ptr.hpp unordered_map.hpp cobalt.hpp histogram numeric scope_exit.hpp unordered_set.hpp compressed_pair.hpp histogram.hpp operators.hpp serialization url concept hof operators_v1.hpp shared_array.hpp url.hpp concept_archetype.hpp hof.hpp optional shared_ptr.hpp utility concept_check icl optional.hpp signals2 utility.hpp concept_check.hpp interprocess parameter signals2.hpp uuid config intrusive pending smart_ptr uuid.hpp config.hpp intrusive_ptr.hpp phoenix smart_ptr.hpp variant container io phoenix.hpp sort variant2 context io_fwd.hpp pointer_cast.hpp spirit variant2.hpp convert json pointer_to_other.hpp spirit.hpp variant.hpp convert.hpp json.hpp polygon stacktrace version.hpp cregex.hpp leaf pool stacktrace.hpp vmd cstdfloat.hpp leaf.hpp predef statechart wave cstdint.hpp limits.hpp predef.h static_assert.hpp wave.hpp cxx11_char_types.hpp locale program_options static_string weak_ptr.hpp date_time locale.hpp program_options.hpp static_string.hpp winapi date_time.hpp local_function progress.hpp stl_interfaces xpressive describe local_function.hpp property_map system yap describe.hpp lockfree proto system.hpp detail logic ptr_container test dynamic_bitset make_default.hpp python thread dynamic_bitset_fwd.hpp make_shared.hpp python.hpp thread.hpp uidq8326@hzh27145u:/work/pcl-cross-compile/src/boost$ ./b2 install toolset=gcc architecture=arm address-model=64 \--prefix=/work/pcl-cross-compile/install/boost -j$(nproc) Performing configuration checks - default address-model : 64-bit [1] - default architecture : arm [1] - symlinks supported : yes error: Unable to find file or target named error: '/boost/headers' error: referred to from project at error: 'libs/date_time/build'
最新发布
08-19
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值