Sunday, 16 March 2014

What are smart pointers?

Pointers are extremely useful, but they are also the source of hard-to-detect memory leaks. "Smart" pointers attempt to address this problem.

Every time we call new, there should be a corresponding delete. Unfortunately, simply remembering to do things is not bulletproof. It would be great if the pointer automatically takes care of itself by executing some piece of code when it is no longer needed. Wait, doesn't that sound like a... destructor?

Thus we see how the idea of smart pointers is born. In its essence, a smart pointer encapsulates a pointer in a class. The smart pointer is declared on the stack. When the instance of the class goes out of scope, for example, the destructor (which contains the clean up code) is automatically called.

Now that the pointer is encapsulated in a class, it is only logical to go one step further and add more features as required, e.g. reference counting so that the memory is only freed when nothing else is referencing it. Further reading: C++11 has unique_ptr, shared_ptr, and weak_ptr.

No comments:

Post a Comment