《C++标准程序库》读书笔记 2012-07-12 auto_ptr_ref记录
2012-07-12 00:32
295 查看
正常情况下,一个类别的copy构造和赋值是需要使用const T&,因为auto_ptr本身copy构造和赋值的特殊性,只能使用T&,不能使用const T&,否则无法转移ownership,
源码如下:
不过以上这种写法会导致一些问题,以下代码将演示copy构造和赋值需要const T&,
示例如下:
输出结果:
Call Test()
Press any key to continue
这表示对于语句Test t2(Test());没有调用Test(Test& rt) ,而是使用默认的copy构造函数Test(const Test&)。
所以auto_ptr也会如Test一样,在使用临时对象进行构造的时候,使用编译器默认生成的copy构造函数auto_ptr(const auto_ptr<_Ty>& _Right),
不过这将导致编译失败,因为const常数性,将会导致无法修改_Right的ownership。
所以需要使用辅助类auto_ptr_ref进行一些变通操作,将const auto_ptr&转成auto_ptr_ref,然后就能调用auto_ptr(auto_ptr_ref<_Ty> _Right)。
附上参考链接
http://www.iteye.com/topic/746062
源码如下:
auto_ptr(auto_ptr<_Ty>& _Right) _THROW0() : _Myptr(_Right.release()) { // construct by assuming pointer from _Right auto_ptr } auto_ptr<_Ty>& operator=(auto_ptr<_Ty>& _Right) _THROW0() { // assign compatible _Right (assume pointer) reset(_Right.release()); return (*this); }
不过以上这种写法会导致一些问题,以下代码将演示copy构造和赋值需要const T&,
示例如下:
class Test { public: Test() : _v(0) { std::cout << "Call Test()" << std::endl; } //no general copy constructor Test(Test& rt) : _v(rt._v) { std::cout << "Call Test(Test&)" << std::endl; } private: int _v; }; int main() { Test t; //use temp object Test t2(Test()); //here no call Test(Test& rt) method. return 0; }
输出结果:
Call Test()
Press any key to continue
这表示对于语句Test t2(Test());没有调用Test(Test& rt) ,而是使用默认的copy构造函数Test(const Test&)。
所以auto_ptr也会如Test一样,在使用临时对象进行构造的时候,使用编译器默认生成的copy构造函数auto_ptr(const auto_ptr<_Ty>& _Right),
不过这将导致编译失败,因为const常数性,将会导致无法修改_Right的ownership。
所以需要使用辅助类auto_ptr_ref进行一些变通操作,将const auto_ptr&转成auto_ptr_ref,然后就能调用auto_ptr(auto_ptr_ref<_Ty> _Right)。
附上参考链接
http://www.iteye.com/topic/746062
相关文章推荐
- 《C++标准程序库》读书笔记 2012-07-08 auto_ptr 作为参数传递
- 《C++标准程序库》读书笔记 2012-07-07 auto_ptr 禁止隐式转换
- 关于auto_ptr_ref的一点问题
- ACE学习手记--- 智能指针(ACE_Auto_Ptr / ACE_Refcounted_Auto_Ptr)
- auto_ptr_ref的奇妙(上)
- auto_ptr中的auto_ptr_ref
- auto_ptr_ref的奇妙
- 为什么需要auto_ptr_ref
- auto_ptr源码解析以及例子 --auto_ptr_ref
- 为什么需要auto_ptr_ref
- auto_ptr_ref的奇妙(下)
- auto_ptr_ref
- 关于auto_ptr_ref的一点问题
- 一个auto_ptr_ref引发的连锁思考
- 关于auto_ptr_ref的一点问题
- auto_ptr中auto_ptr_ref的作用
- 为什么需要auto_ptr_ref
- auto_ptr与auto_ptr_ref
- 浅析为什么要有auto_ptr_ref这个类
- auto_ptr、auto_ptr_ref及它们存在的问题