Class constructed only on stack; not with new. C++

It's impossible to prevent an object being created on the heap. There are always ways around it. Even if you manage to hide operator new for Foo, you can always do:

#include <new>

struct Foo {
        int x;
private:
        void* operator new (std::size_t size) throw (std::bad_alloc);
};

struct Bar
{
    Foo foo;
};

int main()
{
    Bar* bar = new Bar;
    return 0;
}

And hey presto, you have a Foo on the heap.


Make your operator new private.

#include <new>

struct Foo {
        int x;
private:
        void* operator new (std::size_t size) throw (std::bad_alloc);
};

On C++0x you can delete the operator new:

struct Foo {
        int x;
        void* operator new (std::size_t size) throw (std::bad_alloc) = delete;
};

Note that you need to do the same for operator new[] separately.


In your documentation, put "do not create on the heap". Explaining why would be a good idea. Note that any attempt to enforce stack-only construction will also prevent the class from being used in standard containers and similar classes - it's not a good idea.

Tags:

C++