Re: Question on use of "placement" new
On 17 Maj, 18:15, l...@grame.fr wrote:
Hi,
We have a class whose objects are to be allocated in shared memory. To
do that a ShmManager base class is defined so that operator new and
delete are redefined to allocate segments in shared memory. A typical
class "Foo" then inherit from ShmManager to have get this behaviour.
class ShmManager {
void* operator new(size_t size);
void operator delete(void* p, size_t size);
};
class Foo : public ShmManager
{
int fData1;
Barr fData2[16];
};
In the previous Foo example, the size of fData2 array is known at
compilation time, but we need to make this size "dynamic", but keeping
the object memory layout "flat".
Why must it be flat? You can't do that portably in C++ and there are
potential problems here - e.g. if Barrs alignment is not compatible
with that of int.
I will assume that a solution where fData2 is a pointer to memory not
adjacent to fData1.
We are using the "placement" new syntax doing:
class Foo1 : public ShmManager
{
int fData1;
Barr fData2[]; // will be extented using "placement=
" new
};
ShmManager* ptr = ShmManager::operator new(sizeof(Foo1) + num *
sizeof(Barr));
Foo1* = new(ptr) Foo1();
There is no reason to inherit from ShmManager here. This would have
been necessary only in the case where you would be able to new Foo1
directly.
So that Foo1 object nows gets a dynamic "num" number of elements. This
seems to work, but is this safe to do that? Are we obliged to put the
fData2 fied as the *last* element in the Foo1? Is there any better/
safer manner to implement the same pattern?
There are problems:
* your code will have 16 calls to the Barr constructor and this is
only correct when num is 16. To solve this problem, you need to extend
your code.
* The alignment problems mentioned before.
* The nonportability. The code above is not valid C++, and you might
get into troubles for that.
If the requirement was that only the fData2 elements would have to be
contigious, much better solutions exist. Your solution is nonportable
and fragile, but sometimes you just might have to live with that.
/Peter