Can we place dynamically allocated objects at some other place than heap?? How will I define an overloaded new operator for that??
If I have some class Arena like
class Arena{
char area[2000];
public:
Arena(){}
};
Arena my_arena(1000);
And I want to allocate objects from Arena my_arena..
Further, what are the possible drawbacks in such memory allocation as compared to allocation from the heap on the performance etc??
You can easily use placement new for this:
There are two issues you have to be aware of, however:
`MyClass`. I usually solve this by means of a union:
union { double dummyForAlignment; // Any other types which might be necessary... unsigned char area[2000]; };This is very ad hoc; there’s no formal guarantee as to what types you
have to add to be sure. In practice, instead of `double`, I use a union
of most of the basic types, plus a couple of pointers, just to be sure.
new, the compiler won’t take care ofdestruction for you, as it would for a normal data member. You’ll have
to call the destructor explicitly:
p->~MyClass();Which means that you’ll have to keep track of how many objects of what
types, and where, have been allocated.
The drawbacks of this technique are the two points I’ve just mentionned.
Plus, unless you keep a typed pointer to the constructed objects, you may
have problems viewing them in a debugger.
Still, it’s a useful technique for some specific uses: I use it in my
Fallibleclass, in order to avoid the need of default constructor; thestandard containers require it, and of course, pre-standard vector or
array classes generally used it as well. It’s also useful for various
variant classes; I presume it is used in
boost::variant, for example.