[英]In Effective C++ Item 3,why use static_cast<const TextBlock&>(*this) instead of static_cast<const TextBlock>(*this)?
I'm reading Scott Meyers's Effective C++ 3rd. 我正在阅读Scott Meyers的Effective C ++ 3rd。
In item 3: 在第3项中:
Use const whenever possible.
尽可能使用const。 In order to use const member function operator[],non-const member function operator[] has to do 2 cast operations:
为了使用const成员函数operator [],非const成员函数operator []必须做2个强制转换操作:
const_cast<char&>( static_cast<const TextBlock&>(*this) [position] )
Why does Scott Meyers use static_cast<const TextBlock&>(*this)
instead of static_cast<const TextBlock>(*this)
? 为什么Scott Meyers使用
static_cast<const TextBlock&>(*this)
而不是static_cast<const TextBlock>(*this)
?
static_cast<const TextBlock>(*this)
will create a temporary object, which is copied from *this
. static_cast<const TextBlock>(*this)
将创建一个临时对象,该对象从*this
复制。 And then operator[]
will be invoked on it, and the returned char&
will be dangled when go out of the non-const member function operator[]
. 然后将调用
operator[]
,并且当退出非const成员函数operator[]
时,返回的char&
将被悬空。 Note that dereference on it leads to UB. 请注意,取消引用它会导致UB。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.