to delete: heap-stack dual variable #ptr/ref

Common scenario — you declare a local ptr variable and assign it q(new int), you get a heap-stack var. The object lives on the heap but the ptr var lives on the stack (unless the variable itself is optimized away).

Unfortunately, when the ptr var goes out of scope, you lose the address forever and can’t free the memory.

One best practice is to always new() and delete() an object in the same func, or use smart ptr

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s