reinterpret_cast是否会导致未定义的行为? [英] Does reinterpret_cast lead to undefined behavior?

查看:107
本文介绍了reinterpret_cast是否会导致未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类模板 A ,其中包含一个指针容器( T * ):

I have a class template A which contains a container of pointers (T*):

template <typename T>
class A {
public:
   // ... 
private:
   std::vector<T*> data;
};

和一系列函数,如:

void f(const A<const T>&);
void g(const A<const T>&);

是否可以通过 A< const T> ; A< T>

A<double> a;
... 
auto& ac = reinterpret_cast<const A<const double>&>(a);
f(ac);

我很确定此代码具有未定义的行为。

I'm pretty sure that this code has undefined behaviour.

在现实生活中使用此类转换是否危险?

Is it dangerous to use such conversions in real life?

推荐答案

A< double> A< const double> 是不相关的类型,实际上是未指定的(最初我认为是未定义的)行为,因此是的,在现实生活中使用它是一个坏主意:您永远不知道什么系统或编译器( s)您可能会认为行为的改变是奇怪的方式。

As A<double> and A<const double> are unrelated types, it's actually unspecified (originally I thought undefined) behavior and correspondingly yes it's a bad idea to use in real life: You never know what system(s) or compiler(s) you may port to that change the behavior is strange ways.

参考:

5.2.10 / 11:

5.2.10/11:


如果类型为T1的左值表达式可以转换为对
T2的引用可以使用reinterpret_cast将 T1指针显式地将
转换为 T2指针类型。
是一个参考强制转换reinterpret_cast(x)与
具有内置&转换* reinterpret_cast(& x)的效果相同。和*
运算符(以及类似的reinterpret_cast(x))。

An lvalue expression of type T1 can be cast to the type "reference to T2" if an expression of type "pointer to T1" can be explicitly converted to the type "pointer to T2" using a reinterpret_cast. That is, a reference cast reinterpret_cast(x) has the same effect as the conversion *reinterpret_cast(&x) with the built-in & and * operators (and similarly for reinterpret_cast(x)).

所以他们将我们重定向到了前面的部分。 5.2.10 / 7:

So they've redirected us to an earlier section 5.2.10/7:


对象指针可以显式转换为
a类型的对象指针。 ... ...将
类型的指向T1的指针的prvalue转换为指向T2的指针的类型(其中T1和T2是
对象类型,而T2的对齐要求不是
比T1严格)并返回其原始类型,将产生
原始指针值。未指定任何其他此类指针
转换的结果。

An object pointer can be explicitly converted to an object pointer of a different type. ... ... Converting a prvalue of type "pointer to T1" to the type "pointer to T2" (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value. The result of any other such pointer conversion is unspecified.

如果 f g 是适用于容器的算法,简单的解决方案是将其更改为适用于范围(迭代器对)的模板算法。

If f and g are algorithms that work on containers, the easy solution is to change them to template algorithms that work on ranges (iterator pairs).

这篇关于reinterpret_cast是否会导致未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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