Objects with Special Storage Restrictions

Sometimes restriction of object storage is usefull.

Objects only in the Heap

The following class could be created only by new operator in the heap. This is important when new takes extra parameters, or defines special semantics: like persistency or garbage collection.


//
//  Objects only in heap:
//

#include <new>

class X
{
public:
    X() {}
    void destroy() const { delete this; }
protected:
    ~X() {}
};

class Y : public X { };
//  class Z { X xx; };  // use pointer!

The usage:


// X x1;
int main()
{
//  X x2;
//  Y y1;
    X* xp = new X;
    Y* yp = new Y;

//  delete xp;
    xp->destroy();
    delete yp;
};

It is still possible to create objects of X and Y in the stack or as static variable. We can define placement new the same way as we did with new.

Objects not in the Heap


#include <new>

class X
{
private:
    static void *operator new( size_t);
    static void operator delete(void *);
};

class Y : public X { };

Usage:


X x1;
int main()
{
    X x2;
    Y y1;
//  X* xp = new X;
//  Y* yp = new Y;

//  delete xp;
//  delete yp;
};