Home > other >  Is this downcast undefined behaviour?
Is this downcast undefined behaviour?

Time:01-27

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;
}

CodePudding user response:

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.

CodePudding user response:

I think this is well defined:

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

class Concatenator : public std::pair<const std::string, std::string> {
public:
    using base = std::pair<const std::string, std::string>;
    Concatenator(const base& o) : base(o) {}
    operator std::string() const { return first   ", "   second; }
};

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

  Concatenator c = *m.begin();
  std::cout << std::string{c} << std::endl;
}
  • Related