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;
};
- stl中使用智能指针的问题
- C++中智能指针的使用
- C++中智能指针的简单使用
- osg中智能指针的使用
- 智能指针的使用
- 智能指针的使用
- 智能指针的使用
- 智能指针的使用
- stl中auto_ptr,unique_ptr,shared_ptr,weak_ptr四种智能指针使用总结
- stl智能指针auto_ptr
- STL--智能指针(auto_ptr)
- STL 智能指针
- stl智能指针auto_ptr
- STL之智能指针
- STL之智能指针
- auto_ptr STL智能指针
- 【STL】智能指针auto_ptr
- 智能指针(STL)
- JavaMail类
- 强制类型转换
- 给年轻程序员的建议
- 作为嵌入式程序员需要了解的基本知识
- 网页背景图片拉伸解决办法。。
- stl中使用智能指针的问题
- html中border标签
- 【转】oracle表分区详解
- HDOJ/HDU 2082 母函数 找单词 2006/1/15 ACM程序设计期末考试
- 别让电脑"辐射斑"爬上小嫩脸
- 关于博客的迁移
- Flex 弹出窗口--datagrid--自定以事件
- YUV 4:2:0 格式和YUV411格式区别
- InetAddress类的一些方法