A class built only on the stack; not with a new one. C ++

Is there a way to create a Foo class

so that I can:

Foo foo; 

but not

 Foo* foo = new Foo(); 

?

I do not want people to be able to allocate copies of Foo on the heap.

Thanks!

EDIT: Sorry, I made a mistake on the "stack, not the heap." I want to say that "you cannot use the new operator."

+4
source share
5 answers

Make your operator new private.

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

In C ++ 0x, you can delete 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 the new[] operator separately.

+5
source

There is no way to prevent the creation of an object on the heap. There are always ways around this. 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 foo on the heap.

+14
source

In your documentation, put "do not create on the heap." An explanation of why it would be a good idea. Note that any attempt to force the creation of a structure only for the stack will also prevent the use of the class in standard containers and similar classes - this is not a good idea.

+5
source

You can give the class a private new statement. See Open statement, new, private delete operator: getting C2248 "cannot access private member" when using new ones for more information.

+3
source

Why don't you want people to create Foo on the heap? I can come up with absolutely no reason why this would be useful.

In any case, you can provide your class with a private operator new to accomplish this, but note that this will also prevent people from using your class in standard containers, since they all heap the objects contained in it. It is just a bad idea to do what you are trying to do.

-1
source

Source: https://habr.com/ru/post/1301895/


All Articles