0

Possible Duplicate:
How do I prevent a class from being allocated via the 'new' operator? (I'd like to ensure my RAII class is always allocated on the stack.)

For C++, how to enforce that classes's instances only be allocated on the stack, but not on the heap, at compile-time?

I think all data members and functions are allocated in stack unless they are declared by new operator.

right ?

Any help is really appreciated.

Community
  • 1
  • 1
Jack
  • 133
  • 1
  • 7
  • 3
    You can make `new` for that class private: http://stackoverflow.com/questions/124856/how-do-i-prevent-a-class-from-being-allocated-via-the-new-operator-id-like-t – wkl Aug 27 '11 at 03:58

1 Answers1

3

Declare, but don't define, a custom new/delete for the class.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
  • If you have C++11, will `operator new(whatever) = delete` work as well? Also cool trick, +1. – Seth Carnegie Aug 27 '11 at 04:04
  • @Seth: I don't know. If legal, then I expect it will achieve the same effect. – Marcelo Cantos Aug 27 '11 at 04:09
  • Also will this work with placement new? – Seth Carnegie Aug 27 '11 at 04:13
  • @Seth, you can't stop someone from allocating on the heap if they're _really trying_. They could, for example, wrap it in a container class and allocate that class on the heap – bdonlan Aug 27 '11 at 04:19
  • @bdonlan They could also just use malloc and cast. Overloading the new operator at least keeps the less evil programmers at bay. – Mranz Aug 27 '11 at 06:26
  • @bdonlan: C++ safety parts are not designed to stop people that want to circumvent them they are designed to stop people accidentally circumventing them. – Martin York Aug 27 '11 at 07:14
  • Interesting discussion. 2c worth from the original answerer: Security is not what the designers of C++ had in mind (unlike Java's locked-down sandbox approach). – Marcelo Cantos Aug 27 '11 at 07:45
  • @Mranz Actually using malloc and casting will result in extremely interesting behavior for any non POD class and placement new wouldn't work either. So using a wrapper is basically the only reliable approach in this case. – Voo Aug 27 '11 at 14:48
  • @Martin, exactly my point. You can lock down regular `new` and `delete`, but then you have placement new, allocation as a member variable, etc. You can't prevent a determined person from shooting themselves in the foot, so don't bother trying. – bdonlan Aug 27 '11 at 17:23
  • @Voo, placement new in a malloc'd buffer is perfectly safe and legal. – bdonlan Aug 27 '11 at 17:24
  • 1
    @bdonlan That's not the point. If new is hidden (and why else do that?), placement new will be hidden just as well and malloc alone without placement new will only work for POD's (they renamed those with c++0x, I just forgot how) – Voo Aug 27 '11 at 18:44