在有效C++第 3 项中,为什么使用 static_cast<const TextBlock&>(*this) 而不是 static_cast<const TextBlock>
In Effective C++ Item 3,why use static_cast<const TextBlock&>(*this) instead of static_cast<const TextBlock>(*this)?
我正在阅读Scott Meyers的《高效C++第三版》
第3项:
尽可能使用常量。为了使用常量成员函数运算符[],非常量成员函数操作符[]必须执行两个强制转换操作:
const_cast<char&>( static_cast<const TextBlock&>(*this) [position] )
为什么Scott Meyers使用static_cast<const TextBlock&>(*this)
而不是static_cast<const TextBlock>(*this)
?
static_cast<const TextBlock>(*this)
将创建一个临时对象,该对象是从*this
复制的。然后operator[]
将被调用,返回的char&
将在退出非常数成员函数operator[]
时挂起。请注意,对它的取消引用会导致UB。