以下简单程序无法使用 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/