gpt4 book ai didi

c++ - c++ primer 是否对 `dynamic_cast` 的使用有问题?

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

引自 C++ Primer 5th 19.2.1。 dynamic_cast 运算符

A dynamic_cast has the following form:

dynamic_cast<type*>(e)
dynamic_cast<type&>(e)
dynamic_cast<type&&>(e)

where type must be a class type and (ordinarily) names a class that has virtual functions. In the first case, e must be a valid pointer (§ 2.3.2, p. 52); in the second, e must be an lvalue; and in the third, e must not be an lvalue.

In all cases,the type of e must be either a class type that is publicly derived from the target type, a public base class of the target type, or the same as the target type. If e has one of these types, then the cast will succeed. Otherwise, the cast fails.
If a dynamic_cast to a pointer type fails, the result is 0. If a dynamic_cast to a reference type fails, the operator throws an exception of type bad_cast

不过,这里我写了一段代码:

struct A {};
struct B : private A // note: *private* inheritance
{
A* test() {
return dynamic_cast<A*>(this);
}
};

int main()
{
B b;
if(b.test()==nullptr)
throw 1;
}

在上面的代码片段中,A 只是B 的私有(private)基,c++ primer 没有考虑到这一点。但是,此代码片段可以编译和运行而不会出错。引子搞错了吗?

最佳答案

总的来说,这是引物部分的一个不幸的措辞。它将人们可以做的两种类型的转换组合成一个句子,然后结果说错了。

转换为基类,不需要运行时转换操作。它是,as T.C. says , 纯粹的静态结构。和 T.C.引用,它需要一个 accessbile 基础,而不是公共(public)基础。所以您的代码一切都很好。

对于运行时强制转换(向下强制转换),C++ 标准对动态强制转换中涉及的操作数和类型提出了要求,以使其成功。该类必须是公开派生的,否则实现没有义务在继承链中成功转换。我的意思是,理论上它可以使转换成功,但根据规范 "the runtime check fails" ,这不会留下太多余地。

但无论哪种方式,您的程序都没有导致编译失败的错误,也没有任何会导致任何类型的运行时错误的错误。


如果我们将您的代码更改为向下转换而不是向上转换,这里是一个 example that doesn't even build :

struct A {};
struct B : private A // note: *private* inheritance
{
A* test(B* p) {
return dynamic_cast<A*>(p);
}

friend B* foo(A*);
};

B* foo(A* a) {
return dynamic_cast<B*>(a);
}

int main()
{
B b;
*foo(&b);
}

AfooB 的可访问基类,但是,转换格式不正确。


将入门类(class)带回类(class)的最小变化是将公开从目标类型派生的类类型”变成“a 可访问从目标类型派生的类类型”。由于 publicly available errata 中没有此类内容,我们可以猜测这是一个尚未指出的编辑错误。

关于c++ - c++ primer 是否对 `dynamic_cast` 的使用有问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49381515/

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