Quantcast
Channel: Would overwriting a polymorphic object byte-by-byte in memory ever be valid in C++? - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Would overwriting a polymorphic object byte-by-byte in memory ever be valid in C++?

$
0
0

This is more of a 'what if' question than a practical one. Assume that I allocate some polymorphic objects in such a way that the allocator always reserves enough room for the largest object. I want to know if you can use memcpy to change the polymorphic type of one object to another.

Out of my head; not tested:

class Animal {  virtual ~Animal() {}};struct Cat : public Animal {  int lives;};struct Dog : public Animal {  size_t bark_count;};Dog* dog = malloc(std::max(sizeof(Dog), sizeof(Cat)));new (dog) Dog(0);Cat* cat = malloc(std::max(sizeof(Dog), sizeof(Cat)));new (cat) Cat(9);// Make cat a dog. Is this possible?memcpy(reinterpret_cast<char*>(cat), reinterpret_cast<char*>(dog), sizeof(Dog));

I'm assuming that due to the question When is a type in c++11 allowed to be memcpyed?, this is invalid behavior. However, I'm not 100% sure, either.

Context: I'm writing a type checker and need to 'rewrite' types as more information comes available. I thought about refactoring the Type class to a union type but it will require a considerable amount of work. Other approaches are very much welcome.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images