您的位置:首页 > 编程语言 > C语言/C++

《C++标准程序库》读书笔记 2012-07-12 auto_ptr_ref记录

2012-07-12 00:32 295 查看
正常情况下,一个类别的copy构造和赋值是需要使用const T&,因为auto_ptr本身copy构造和赋值的特殊性,只能使用T&,不能使用const T&,否则无法转移ownership,
源码如下:

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++ 编译器 class