在Effective C++第3条中,为什么要使用static_cast<const TextBlock&>(*this)而不是static_cast<const TextBlock>(*this)?

4

我正在阅读Scott Meyers的Effective C++第三版。
在第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)?

1
因为那会复制吗? - Columbo
1个回答

3

static_cast<const TextBlock>(*this)会创建一个临时对象,该对象是从*this复制而来的。然后在其上调用operator[],当退出非常量成员函数operator[]时,返回的char&将悬挂不定。请注意,在其上解除引用会导致未定义行为。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接