From the course: Secure Coding in C++
Unlock this course with a free trial
Join today to access over 25,500 courses taught by industry experts.
Solution: Smart pointers - C++ Tutorial
From the course: Secure Coding in C++
Solution: Smart pointers
(upbeat music) - [Instructor] Here's my solution. First, I included the memory header in line seven. Then in line 10, I replaced the raw pointer with a standard unique pointer to an array of int. This way, the memory will be automatically released when the object goes out of scope. Moving on to the constructor in line 15, I now use make_unique instead of calling new. This allocates an array and wraps it in a unique pointer that knows how to delete it properly. That's it. Those are the only changes. Now, let's compile and run it with the address sanitizer to make sure the memory is handled correctly. Let me compile, and then run the executable. And there it is. We get the expected allocation messages, and the program finishes with no memory leaks reported. The smart pointer took care of it for us.