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".
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With