Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

Is there a way to create a class Foo

so that I can do:

Foo foo;

but not

Foo* foo = new Foo(); 

?

I don't want people to be able to allocate copies of Foo on the heap.

Thanks!

EDIT: Sorry, I was wrong on the "stack only, not heap". What I want to say is "can not use new operator".

like image 712
anon Avatar asked Feb 20 '10 10:02

anon


People also ask

How to create object only in stack in c++?

2) For restricting the object creation on heap, Make operator new as private. This code is still creating object on Heap/Free store as it is using new. 3) To create object only on stack not on heap, the use of new operator should be restricted. This can be achieved making operator new as private.

Are classes allocated on the heap?

Class members are part of a class instance. Where they live depends upon where the instance lives. If you declare an instance of a class as an automatic variable, then it is on the stack. If you allocate it with operator new, then it is on the heap.

What is a class stackoverflow?

A Class is like an object constructor or a "blueprint" for creating objects. A reference is an address that indicates where an object's variables and methods are stored.


2 Answers

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.

like image 102
Steve Folly Avatar answered Nov 10 '22 13:11

Steve Folly


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.

like image 40
kennytm Avatar answered Nov 10 '22 14:11

kennytm