gpt4 book ai didi

c++ - 这保证是一个安全的类型转换吗?

转载 作者:太空狗 更新时间:2023-10-29 23:52:16 25 4
gpt4 key购买 nike

考虑以下定义:

struct A {
// ...
};

struct B : public A {}; // empty

void f(B& b) { /* use b */}

void g(A& a) {
f(static_cast<B&>(a)); // is this a safe downcast?
}

int main() {
A a;
g(a);
}

在上面的示例中,a 实际上是 A 的一个实例。

由于 B 有一个空定义,我想知道在这种特定情况下对 f 的调用及其执行是否是未定义的行为。

最佳答案

不,这不是合法的转换,因为它是在一个不是 B 类型的对象上执行的。你的程序有未定义的行为。

根据 C++11 标准的第 5.2.9/2 段:

An lvalue of type “cv1 B,” where B is a class type, can be cast to type “reference to cv2 D,” where D is a class derived (Clause 10) from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is neither a virtual base class of D nor a base class of a virtual base class of D. The result has type “cv2 D.” An xvalue of type “cv1 B” may be cast to type “rvalue reference to cv2 D” with the same constraints as for an lvalue of type “cv1 B.” If the object of type “cv1 B” is actually a subobject of an object of type D, the result refers to the enclosing object of type D. Otherwise, the behavior is undefined

关于c++ - 这保证是一个安全的类型转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16567005/

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