作者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