C++: The Advantages of Smart Pointers
By using a smart pointer instead of a regular pointer, the pointer automatically manages its own memory allocation and deallocation. Thus no manual memory management is necessary.
Smart pointers have a significant advantage over C-style pointers, especially in larger projects where manual memory management becomes infeasible. Memory leaks are more likely to occur using C-style pointers due to the size of the project, and managing new and delete allocations and deallocations is time lost that could be better spent elsewhere.
Thus, the argument can be made that smart pointers increase productivity, and improve the robustness of the program. The programmer will never need to worry about headaches down the track concerning memory management.
For this reason alone, using smart pointers is an advantage for using C++ instead of C, at least in the application development domain. Using smart pointers has a very small overhead, and hence C-style pointers should be avoided in general-purpose programming when using C++. Herb Sutter, a prominent C++ expert and member of the C++ ISO Standards committee, claimed in his recent talk, ‘(Not Your Father’s) C++’ that the committee is no longer recommending people to use the keywords ‘new’ and ‘delete’.
Using these keywords makes any program prone to human error, and hence allowing smart pointers to do the work for you is much safer.
Let’s look at an example.
The following line creates a unique pointer of type ‘Employee’, and allocates memory for the object ‘foo’ the size of Employee. It is analogous to:
Employee *foo = new Employee;
So, the smart pointer way:
std::unique_ptr<Employee> foo(new Employee);
For reference, here is the Employee class:
class Employee
{
public:
void setName(std::string);
std::string getName();
private:
std::string m_name;
};
While using C-style pointers requires fewer keystrokes, using smart pointers means that the programmer does not need to explicitly call ‘delete’, which is an invaluable advantage. This is especially advantageous when the programmer has to look after multiple instances of memory allocation and deallocation.
I want to digress slightly and mention the never-ending C vs C++ war. It seems that the vast majority of people who criticise C++ have either never used it in its modern form, especially with C++11, or were too closed minded too look outside of C’s procedural programming paradigm.
I am no expert programmer, but I’m beginning to see C++ develop into its own language. For a long time, it seemed like a half-hearted experimental C remix. Now, it definitely feels like a highly polished language in its own right. The comparison between C and C++, therefore, is irrelevant in today’s world: C will always be the minimal, simple language that it was created to be, and C++ is now (finally) taking gallant steps forward to keep C++ relevant in today’s world.
Has it done it? Certainly. And, I assure you, it will only improve from here on.