作者tomap41017 (绝梦)
看板EE_DSnP
标题Re: [问题] const_cast的问题
时间Thu Oct 14 23:44:21 2010
const_cast还可以用在
以下出自effective c++ 3rd, Item 3
「When const and non-const member functions have essentially identical
implementations, code duplication can be avoided by having the non-const
version call the const version.
Char& operator[] (std::size_t position)
{ return const_cast<char&>( //cast away const on op’s return type
static_cast<const TextBlock&>(*this)//add const to *this’s type
[position] );} //call const version op[]」
意思就是说,如果一个member function 的 const version 与 non-const version,
其实是做一样的事情的话,可以令non-const去呼叫const的版本。
还记得吗?一个non-const object可以呼叫const member function,是不违反常数性的,
但是当两个版本(const and non-const)同时存在时,non-const object会自动匹配至
non-const版本,故只有non-const member function会被呼叫。
而当我们在non-const member function中转呼叫时,必须先把*this用static_cast
转成const reference,因此这样呼叫到的就是const version member function;
而当此member function return时,可能return a const reference to inner data,
但是呼叫这个function的是一个non-const function的转呼叫,而其是从一个
non-const object呼叫来的,他预期拿到的(可能)是non-const reference to inner
data,而不是const版本,因此我们需要把回传值的常数性去掉,这时就用到了
const_cast。
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.112.244.171
1F:推 ric2k1:感谢补充! 10/15 00:13
2F:推 scuendless:wow好多文!! 感谢大家回答!!!! 10/15 00:15