在 Effective C++ Item 3 中,为什么使用 static_cast<const TextBlock&>(*this) 而不是 static_cast<const TextBlock>(*this)?
In Effective C++ Item 3,why use static_cast<const TextBlock&>(*this) instead of static_cast<const TextBlock>(*this)?
我正在阅读 Scott Meyers 的 Effective C++ 3rd。
在第 3 项中:
Use const whenever possible. In order to use const member function operator[],non-const member function operator[] has to do 2 cast operations:
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&
会在非const成员函数operator[]
外挂起。请注意,对它的取消引用会导致 UB。
我正在阅读 Scott Meyers 的 Effective C++ 3rd。
在第 3 项中:
Use const whenever possible. In order to use const member function operator[],non-const member function operator[] has to do 2 cast operations:
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&
会在非const成员函数operator[]
外挂起。请注意,对它的取消引用会导致 UB。