A basic tenet of modern C++ programming; for leak-free code, you must use std::unique_ptr and/or std::shared_ptr by default. Any time you allocate memory, it should be placed immediately into a smart pointer. Ideally, the smart pointer’s initialization will also occur on the same line of code as the memory allocation:
// Allocate memory in the unique_ptr’s constructor
unique_ptr<int> myPtr(new int(12));
// Alternatively, use the standard make_unique helper method, and the ‘auto’ keyword;
auto myPtr2 = make_unique<int>(12);
There are times, however, when your application must interact with – *gasp!* – legacy APIs. Legacy APIs which might allocate memory before handing off ownership to you, the client. This article will discuss clean, convenient ways to ensure that memory allocated from a ‘legacy’ API is reliably placed into a smart pointer.