I stumbled upon code like this:
void foo(T* bar); // Note: takes ownership of 'bar'.
foo(new T());
And now I wonder if there is any point in refactoring it to:
void foo(T* bar); // Note: takes ownership of 'bar'.
auto tempT = std::make_unique<T>();
foo(tempT.release());
Note that I unfortunately can't change the signature of 'foo'.
Is it more exception-safe?
No. However, consider a slightly more complex example:
auto tempT = std::make_unique<T>();
some_operation();
foo(tempT.release());
In this case, there would be a potential issue with exception safety if unique_ptr wasn't used.
That said, much safer would be:
void foo(std::unique_ptr<T> bar); // no need to note that takes ownership
// because that's implied by the type
Note that I unfortunately can't change the signature of 'foo'.
Then write a wrapper function that you can control.
No it is not more exception safe.
But consider if function changes to take more parameters:
void foo(T* bar, T* more_bar = get_more_bar()); // Note: takes ownership of both.
foo(new T());
Now what if get_more_bar()
is evaluated after new T()
and throws.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With