0

The question is whether the following is undefined behaviour (and if not, what guarantees do I have):

    using kv = std::pair<std::string, int>;
    using ckv = std::pair<const std::string, int>;
    kv x = {"239", 239};
    const kv* p = &x;
    std::cout << p->first << " " << p->second << "\n";
    // Dangerous cast
    const ckv* cp = static_cast<const ckv*>(static_cast<const void*>(p));
    std::cout << cp->first << " " << cp->second << "\n";

I know that kv and ckv are two different types and hence pointers are incompatible, but perhaps I am wrong? The snippet above compiles on my machine and does the expected thing - is it just a "happy coincidence" due to two types having similar layout that hides undefined behaviour or is it something I can depend on reliably?

antonpp
  • 2,271
  • 22
  • 28
  • const and non-const nested types have always same layout. If there are no special specializations of templates for const types. And pair shoudn't have any different handling of const and non-const. – Arty Dec 24 '21 at 18:02
  • I'd change the dangerous cast from `const ckv* cp = static_cast(static_cast(p));` to `const ckv* cp = reinterpret_cast(p);`. Unless I'm mistaken (and I may be, I'm not a *language lawyer* anymore), this is a case of "I (the developer) have insider information unavailable to the compiler that makes this seemingly dangerous cast perfectly copacetic." – Eljay Dec 24 '21 at 18:52
  • @Eljay The two lines are exactly equivalent here. It is how `reinterpret_cast` between pointer types is defined. – user17732522 Dec 24 '21 at 20:37
  • Dupe: https://stackoverflow.com/questions/14272141/is-casting-stdpairt1-t2-const-to-stdpairt1-const-t2-const-safe – rustyx Dec 24 '21 at 20:53
  • @user17732522 • True, and a C style cast would be exactly equivalent as well. – Eljay Dec 24 '21 at 21:38

0 Answers0