Search code examples
c++referenceeffective-c++

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.
In item 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]
)

Why does Scott Meyers use static_cast<const TextBlock&>(*this) instead of static_cast<const TextBlock>(*this)?


Solution

  • static_cast<const TextBlock>(*this) will create a temporary object, which is copied from *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[]. Note that dereference on it leads to UB.