Variables on the stack

I think one very underused feature in C++ today is simply storing objects on the stack. Many developers who have started writing C# or Java are used to always using new to declare a variable and do the same thing when they are writing C++. And when they later learn that you should never write a naked new, they instead start using unique_ptr or shared_ptr to manage the lifetime of their objects. What they are forgetting is that many times is it sufficient to simply store the instance that you are creating on the stack as a solid object, either as a member of a class or in the local function scope.

The standard library does this all the time, you write

never ever

If you are certain what type of object you need and when you need it, then simply put it on the local stack!

For often called methods you will get a performance increase by doing this since the allocation of an object on the free store takes some time (new has to locate a free portion of memory to allocate).

The exceptions where you don’t want to allocate the object on the local stack include cases where you may want polymorphic behavior, or the class contains large amounts of data making the object too large for the stack.

Facebookgoogle_pluslinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *