Is it possible to make a recursive placement allocation?
if I have this class:

class A
{
private:
   int m_filed1;  
   char* m_field2;

public:
   A(int size)  
{  
  m_field1 = size;
  m_field2 = new char[size];
}

};

and I want to dynamically allocate it on a specific buffer, I'd like that m_field2 will be too allocated on that buffer and so will every object which I'll define inside "A".
Can it be done?

有帮助吗?

解决方案

You'll need to do some memory management. First of all, you'll need to pass buffer handler to your class constructor. Inside the constructor you'll have to find an offset where you can store the dynamically allocated members and finally you'll need to use placement new for the members as well. Something like this:

class A
{
private:
   int m_filed1;  
   char* m_field2;
   char* m_field3;
public:
   A(int size, char *buffer)  
{  
  m_field1 = size;
  m_field2 = new (buffer + sizeof(A)) char[size];
  m_field3 = new (buffer + sizeof(A) + sizeof(m_field2)) char[size];
  //...
}

};

Invoke by A* objA = new (mybuffer) A(size, mybuffer);

Edit: you might get away without passing the buffer to the constructor (not sure though and might depend on the compiler, need checking):

class A
{
private:
   int m_filed1;  
   char* m_field2;
   char* m_field3;
public:
   A(int size)  
{  
  m_field1 = size;
  m_field2 = new ((char*)this + sizeof(A)) char[size];
  m_field3 = new ((char*)this + sizeof(A) + sizeof(m_field2)) char[size];
  //...
}

};

Invoke by A* objA = new (mybuffer) A(size);

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top