Re: Question on use of "placement" new
letz@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 this behaviour.
class ShmManager {
void* operator new(size_t size);
void operator delete(void* p, size_t size);
};
If you overload operator new, and delete, you should also provide the
corresponding array types (operator new[], operator delete[]).
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".
We are using the "placement" new syntax doing:
class Foo1 : public ShmManager
{
int fData1;
Barr fData2[]; // will be extented using "placement" new
This syntax is invalid in C++. It is valid in C99. C++ requires a
non-zero array size here.
};
ShmManager* ptr
= ShmManager::operator new(sizeof(Foo1) + num * sizeof(Barr));
Foo1* = new(ptr) Foo1();
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?
You might get away if your compiler supports the syntax (thus extends
C++), and (hopefully) if class Fool and Barr are PODs. Specifically, do
not expect that operator= and a copy constructor work reasonably.
Specifically, the Barr's won't be copied. So, technically, no, it is not
safe.
The better way to do that is to make fData2 a pointer to the array (or
better a vector container) and allocate the array or the vector contents
in the constructor of Fool, plus provide the correct assignment operator
and copy constructor.
Greetings,
Thomas
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]