stl中使用智能指针的问题

来源:互联网 发布:linux自动挂载磁盘 编辑:程序博客网 时间:2024/06/05 22:50

1、stl中使用智能指针的问题存在安全性问题的根源:

     看源码:

template <class T>
class CComPtr : public CComPtrBase<T>

------------------------------------

template <class T>
class CComPtrBase

{

......

    T** operator&() throw()
    {
        ATLASSERT(p==NULL);
        return &p;    // p本来就是指针
    }

......

}


问题出现在了智能指针中重载了&取地址运算符,并且这个运算符号是对指针再取了一次取地址,返回的是  T**!

而STL中的值要求里面的参数需要重载拷贝函数,拷贝函数实现的算法中有些会用到&运算,这时智能指针出现了不安全的情况!(并不是都不安全,跟stl中的算法有关,只要不取&来直接用就没关系)


解决方法:

1、再将comptr指针包一层,重载&,取到真正的T*即可


ATL中有一个类已经完成此实现:CAdapt

// Class to Adapt CComBSTR and CComPtr for use with STL containers
// the syntax to use it is
// std::vector< CAdapt <CComBSTR> > vect;


template <class T>
class CAdapt
{
public:
    CAdapt()
    {
    }
    CAdapt(__in const T& rSrc) :
        m_T( rSrc )
    {
    }

    CAdapt(__in const CAdapt& rSrCA) :
        m_T( rSrCA.m_T )
    {
    }

    CAdapt& operator=(__in const T& rSrc)
    {
        m_T = rSrc;
        return *this;
    }
    bool operator<(__in const T& rSrc) const
    {
        return m_T < rSrc;
    }
    bool operator==(__in const T& rSrc) const
    {
        return m_T == rSrc;
    }
    operator T&()
    {
        return m_T; //这里重载,没有再取地址,所以返回了上面的T*,stl就安全了
    }


    operator const T&() const
    {
        return m_T;
    }

    T m_T;
};

原创粉丝点击