const铸造空基类 [英] Const casting empty base class

查看:96
本文介绍了const铸造空基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const_cast删除一个空的基类并在其上调用一个非const方法是否是未定义的行为?例如

Is it undefined behavior to const_cast away an empty base class and call a non const method on it? For example

class EmptyBase {
public:
    void bar() { ... }
};

class Something : public EmptyBase {
public:
    void foo() const {
        const_cast<EmptyBase&>(static_cast<const EmptyBase&>(*this)).bar();
   }
};

我无法在回答该问题的标准(C ++ 14和C ++ 17)中找到相关信息.

I haven't been able to find relevant information in the standards (C++14 and C++17) that answers this..

推荐答案

它本身不是UB.当您丢弃常量并使用获得的glvalue修改最初声明为const的对象时,会得到未定义的行为.这是此内容的标准报价( [dcl.type.cv] /4 ):

It's not UB in and of itself. You get undefined behavior when you cast away constness and use the obtained glvalue to modify an object which is originally declared const. Here's the standard quote on this ([dcl.type.cv]/4):

除了可以声明任何可变的类成员之外,任何其他 尝试在其生命周期内修改const对象会导致 未定义的行为.

Except that any class member declared mutable can be modified, any attempt to modify a const object during its lifetime results in undefined behavior.

仅调用成员函数不是对对象的修改.这完全取决于功能 的作用.因此,如果它做了一些疯狂的事情,例如:

Merely calling a member function is not a modification of an object. It all depends on what the function does. So if it does something crazy like:

std::memset(this, 0, sizeof(*this));

这肯定会导致未定义的行为.但是假设它没有,并且由于没有成员 可以对其进行格式错误的修改,因此通话中不会包含UB.

That would result in undefined behavior, for sure. But assuming it doesn't, and since there are no members for it to modify in an ill-formed manner, there is no UB from the call.

另一个问题(是否是个好主意)有一个明显的答案. const强制转换不应乱扔代码库.但是,如果基类表现良好,尽管定义不明确,但如果您不能更改基类,则可以接受.

The other question, of whether or not it's a good idea, has an obvious answer. Const casts should not litter code bases. But if the base class is well-behaved, albeit not well-defined, it may be acceptable if you can't change the class.

这篇关于const铸造空基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆