1

Let's say there is the following classes:

class A {
    // some data here (let's say - 200 bytes)
public: 
    void foo();
};

class B {
    // some data (150 bytes)
public:
    void bar();
}

And code:

A *a = new A();
a->foo();

B *b = reinterpret_cast<B*>(a);
// then we just stop using a
a = nullptr;    

// and start using this memory as b
b->bar();

Is there an undefined behaviour? (If nowhere else in the code a is no longer used, and I'm sure that 150 first bytes of this memory is quite valid for object b).

All i can find is this. And how can I understand, what I'm doing is an undefined behaviour...

Of course, I understand that there may be a loss when deleting such a piece of memory using delete b;. But can I use this code, or b->bar() is anyway UB?

selya
  • 141
  • 6
  • Yes, it is undefined. Looks like a textbook case of strict aliasing violation to me. If you want to reuse memory so much, use `std::variant`. – HolyBlackCat Mar 05 '18 at 22:12
  • @HolyBlackCat so I can allocate `char[]` and use placement new to construct objects in this memory. But can I just map this memory with `SomeType*` poiners (If im sure that this memory will be rewritten with valid values before first usage)? And is there any differences if this memory was allocated as `SomeOtherType[]`, not `char[]`? – selya Mar 05 '18 at 22:23
  • You're walking on the edge of UB here. It's *probably* ok to reuse storage of `SomeOtherType` if you call destructor of that object manually first (optional if the type is trivially destructable), then placement-new `SomeType` into it (not sure if this is optional for trivially constructible types). Though you have to make sure that the destructor of `SomeOtherType` wont be called on that buffer while it's occupied by `SomeType`, and you have to call destructor of `SomeType` manually. That said, just use `std::variant`. It will do all those things for you. – HolyBlackCat Mar 05 '18 at 22:32

0 Answers0