Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is this downcast undefined behaviour?

I am trying to extend std::map‘s std::pair entries with some extra functionality and want to cast such pairs to a child class of pair. Note that this is the "wrong" direction of polymorphism, the child is not the parent. But since the memory layout should be identical as long as I am not introducing additional members in the child class, I am wondering if this is valid.

Here is a minimal example:

#include <iostream>
#include <map>
#include <string>

class Concatenator : public std::pair<const std::string, std::string> {
public:
  operator std::string() const { return first + ", " + second; }
};

int main() {
  std::map<std::string, std::string> m{{"hello", "world"}};

  // Is this defined behavoiur?
  Concatenator &c{*static_cast<Concatenator *>(&*m.begin())};
  std::cout << std::string{c} << std::endl;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

"But since the memory layout should be identical as long as I am not introducing additional members in the child class…"

No, that’s wrong. That is undefined behavior.

Even without multiple inheritance, there is no guarantee that the memory layout is identical. Even if the memory layout was identical, then it is still undefined behavior. Do not do this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading