gpt4 book ai didi

c++ - 在 Effective C++ Item 3 中,为什么使用 static_cast(*this) 而不是 static_cast(*this)?

转载 作者:太空狗 更新时间:2023-10-29 21:38:05 28 4
gpt4 key购买 nike

我正在阅读 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&退出非常量成员函数时会悬挂 operator[] .请注意,对它的取消引用会导致 UB。

关于c++ - 在 Effective C++ Item 3 中,为什么使用 static_cast<const TextBlock&>(*this) 而不是 static_cast<const TextBlock>(*this)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36173064/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com