我在与const_cast相关的堆栈溢出中发现了两个问题:
1)How do I remove code duplication between similar const and non-const member functions?
2)Is this undefined behavior with const_cast?
假设我们要避免代码重复,如问题1的答案:
for row in ax:
for each_ax in row:
each_ax.legend(['Male', 'Female'])
让我们像这样使用此类:
struct C
{
const char& get() const
{
return c;
}
char& get()
{
return const_cast<char&>(static_cast<const C&>(*this).get());
}
char c;
};
如我所见,我们在getter函数中丢弃了C obj;
obj.get() = 'a';
的常数,并为其赋予了新值,因此根据第二个问题,我们应该获得未定义的行为。
为什么分配给c
不是未定义的行为?
答案 0 :(得分:2)
修改const对象是UB。
obj
未声明为const
。static_cast<const C&>(*this)
是“ just” 的别名。所以你很好。