c++ - 指针类型类成员的动态强制转换的常量性是什么

标签 c++ language-lawyer constants dynamic-cast

以下简单程序无法使用 MSVC 编译,但无法使用 GCC 和 Clang 编译? (即 MSVC 触发 static_assert)。

#include <utility>

class Element {
    virtual ~Element() = default;
};


struct Proxy {

    Element* e{};
};

int main() {

    Proxy p;
    static_assert(std::is_same<decltype(dynamic_cast<const Element*>(p.e)), const Element*>::value, "not const???" );

}

我认为standard非常清楚:

The result of the expression dynamic_cast(v) is the result of converting the expression v to type T. T shall be a pointer or reference to a complete class type, or “pointer to cv void.” The dynamic_cast operator shall not cast away constness ([expr.const.cast]).

标准中是否还有其他部分支持 MSVC,或者是编译器错误?甚至UB?但如果是这样,为什么?

实时代码 here .

最佳答案

它看起来像是一个编译器错误。 [expr.dynamic.cast]/3意味着结果应该是指向 const 限定类类型的指针。

If the type of v is the same as T, or it is the same as T except that the class object type in T is more cv-qualified than the class object type in v, the result is v (converted if necessary).

我强调“必要时进行转换”,因为我相信它适用于类类型的 const 限定。

关于c++ - 指针类型类成员的动态强制转换的常量性是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59704191/

相关文章:

c++ - ffmpeg 问题

c++ - 这部分代码是什么意思?

c++ - 对已删除的数组进行指针运算仍然合法吗?

c - 什么是 C 中的更新流?

c++ - 非平凡类型的模板类析构函数

c++ - constexpr 比 const 多 "constant"吗?

Laravel 验证多个字符串选项

PHP使用未定义常量错误

c++ - 使用堆栈查找加权图的最短路径

c++ - 如何将opencv图片读入caffe格式进行实时预测?