3 ms·
The biggest reason to use make_unique and make_shared is to avoid the ancient C++ problem with non-deterministic order of evaluation. In code like this: //
by int_19h 10y ago
The biggest reason to use make_unique and make_shared is to avoid the ancient C++ problem with non-deterministic order of evaluation. In code like this:
// definition
foo(std::unique_ptr<bar>, std::unique_ptr<baz>);
// call
foo(std::unique_ptr<bar>(new bar), std::unique_ptr<baz>(new baz));
the only guarantee is that `new foo` and `new bar` will occur before the corresponding shared_ptr constructor, and all of them will occur before the call to foo. This means that the following is a valid sequence:
1. new foo
2. new bar
3. unique_ptr
...
Now, if constructor of bar throws, you've leaked foo.
With make_unique, construction and smart pointer acquisition is a single atomic operation - if it throws, everything gets cleaned up.