Differences between std::make_unique and std::unique_ptr with new

The motivation behind make_unique is primarily two-fold: make_unique is safe for creating temporaries, whereas with explicit use of new you have to remember the rule about not using unnamed temporaries. foo(make_unique<T>(), make_unique<U>()); // exception safe foo(unique_ptr<T>(new T()), unique_ptr<U>(new U())); // unsafe* The addition of make_unique finally means we can tell people to ‘never’ use new … Read more

Why can I not push_back a unique_ptr into a vector?

You need to move the unique_ptr: vec.push_back(std::move(ptr2x)); unique_ptr guarantees that a single unique_ptr container has ownership of the held pointer. This means that you can’t make copies of a unique_ptr (because then two unique_ptrs would have ownership), so you can only move it. Note, however, that your current use of unique_ptr is incorrect. You cannot … Read more

RAII and smart pointers in C++

A simple (and perhaps overused) example of RAII is a File class. Without RAII, the code might look something like this: File file(“/path/to/file”); // Do stuff with file file.close(); In other words, we must make sure that we close the file once we’ve finished with it. This has two drawbacks – firstly, wherever we use … Read more