I recently read a lot about "preventing heap allocation for a class" (see this question).
I was able to understand "how", but now I can't figure out "why" someone would like to do that.
I guess there must be legitimate reasons for this, but I just can't figure them out.
In short: "Why may I want to forbid users from creating objects of my class in the heap ?"
For example, you want to create a large size array or big structure to keep that variable around a long time then you should allocate it on the heap. However, If you are working with relatively small variables that are only required until the function using them is alive.
Heap allocation is the most flexible allocation scheme. Allocation and deallocation of memory can be done at any time and any place depending upon the user's requirement. Heap allocation is used to allocate memory to the variables dynamically and when the variables are no more used then claim it back.
Heap memory allocation isn't as safe as Stack memory allocation was because the data stored in this space is accessible or visible to all threads. If a programmer does not handle this memory well, a memory leak can happen in the program.
Some classes make sense only if the objects are instantiated on the stack. For example, Boost scoped_ptr, or lock_guard.
Mainly because stack-allocated objects are automatically cleaned up when they go out of scope, thus removing a large class of bugs - namely memory allocation bugs.
I will go against the tide it seems (so I do expect downvotes, but please leave a comment to indicate the why).
I don't see any reason to forbid heap allocation, mainly because I don't like to second guess the potential uses of the classes I create.
As a design rule, I tend to put as few restrictions on the uses of my classes as possible. This means as few assumptions as possible. There is nothing as maddening as being unable to do what you wish simply because it was forbidden... for reasons either unknown or just plain wrong (denoting the superstitious/erroneous beliefs of the library writer).
Also, pragmatism teach that it's about impossible to actually prevent anything in C++. For example, some people have talked about guards --> what if I'd like to create a super class (which conveniently adds logging) ? Then I would put the guard class as an attribute, and even if its (the original class) new
operator is private, my super class can be instantiated on the heap unless it somehow replicates the mechanism.
So, as for me, it's not a matter of why or how. I just don't fiddle with memory allocation schemes in library code, it's up to the user to use what's most convenient for her.
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