Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

c++ - Does reinterpret_cast lead to undefined behavior?

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

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

and a bunch of functions like:

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

Is it OK to call these functions via a cast from A<const T> to 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Although the reinterpret_cast itself might be unspecified behaviour, attempting to access the parameters once you've done the cast is undefined behaviour.

N3337 [basic.lval]/10: If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined

— the dynamic type of the object,

— a cv-qualified version of the dynamic type of the object,

— a type similar (as defined in 4.4) to the dynamic type of the object,

— a type that is the signed or unsigned type corresponding to the dynamic type of the object,

— a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,

— an aggregate or union type that includes one of the aforementioned types among its elements or non- static data members (including, recursively, an element or non-static data member of a subaggregate or contained union),

— a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,

— a char or unsigned char type.

Your example is none of the above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...