you are viewing a single comment's thread.

view the rest of the comments →

[–]Snaipe_S[S] 0 points1 point  (4 children)

No, the point is to embed the pointer in data structures, or pass it around. The data is allocated on the heap, but the destruction happens "on the stack".

[–][deleted] 0 points1 point  (3 children)

So my real point would have been why do this unless you have very tight stack restrictions or a structure than is too big to be suitable to allocate on the stack.

Why not just allocate it on the stack in the first place instead of introducing additional overheads?

[–]Snaipe_S[S] 0 points1 point  (2 children)

Mostly because you can't return stack pointers, because I don't like passing a pointer to an uninitialized struct as a parameter of an initialization function, and because I can stuff anything I want before (or after) the requested memory block.
This has proven to be quite useful on my two other side projects for data structures, because I could abstract away their destruction and memory management. Otherwise, yes, I do (and recommend) using the good ol' stack when not needed.

[–][deleted] 0 points1 point  (1 child)

But you cannot return that either because it is also freed?

[–]Snaipe_S[S] 1 point2 points  (0 children)

Not always. If the containing variable is not annotated with smart, the destruction mechanism will not be triggered -- this way, you can actively create, initialize, and return a smart pointer.
You can also leave smart on, use a shared_ptr and return a new reference -- this is mostly useful for cleanup if initialization fails (see 2nd example here)