简体   繁体   中英

Is it legal to cast array of wrapper structs containing POD to the array of POD type it contains?

Is this C++ code valid or undefined behaviour? The idea is to be able to wrap a POD you have no control over into another struct to provide helper functions but still be able to use it as if it was the original POD.

struct Data
{
  ...//POD
};
struct Wrapper
{
  Data data;//contains only this
  void HelperFuncA();
  void HelperFuncB();
  ...//only member functions
};

...
//is this legal?
std::vector<Wrapper> vec_of_wrappers;
Data* array_of_data = reinterpret_cast<Data*>(vec_of_wrappers.data());

Now, this code is not valid. There are several reasons for this. First, casting a pointer to the first member of the struct to the struct itself violates strict aliasing rule. This you can fix by making Wrapper a child class of the Data .

The second issue is more problematic, as you are trying to treat an array (vector in this case) polymorphically. sizeof Data is different from the sizeof Wrapper , so an attempt to index an array of Wrapper elements as if it was an array of Data elements will end up pointing into random areas of the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM