C++ memory layout from reseting smart pointer of a base class with different size children

30 Views Asked by At

What happen when we declare a unique_ptr on a singleton and keep reusing this object by resetting it to different child type.

For instances:

class Singlaton{
public:
  void processInformation(Enum::Type) {...}
private:
  unique_ptr<BaseClass> pointer;
}

BaseClass 
{
virtual void executeFunction() = 0;
}

child1 : public BaseClass
{
virtual void executeFunction() final { ... }
char [64] data;
}

child2 : public BaseClass
{
virtual void executeFunction() final { ... }
char [128] data;
}

Singlaton::processInformation(Enum::Type type)
{ 
 switch(type)
 { 
 case x: pointer.reset(BaseClass@child1); pointer->executeFunction();
 case y: pointer.reset(BaseClass@child2); pointer->executeFunction():  
 }
}

while(for a really long time)
 getInput();
 Singlaton.processInformation("ResultFromInput");

Is the memory allocated on the same space? Is this a safe and memory friendly way to handle a situation that requires similar types objects without re-creating it all the time by having a smart pointer on the stack?

Would it be more efficient if the base class have all the data type (ugly) from the children?

Obs: singlaton is only referenced to picture a class that has a long lifetime. I personally do not like it.

0

There are 0 best solutions below