First, write make_unique
:
template<typename T, typename... Args>
std::unique_ptr<T> make_unique( Args&&... args ) {
return {new T(std::forward<Args>(args)...)};
}
which was not included in the standard, basically as an oversight. std::make_shared
is, and make_unique
will probably show up in C++14 or 17.
Second, change your function signature to:
// In some header file:
void f( std::unique_ptr<T1>, std::unique_ptr<T2> );
and call it like:
f( make_unique<T1>(), make_unique<T2>() );
and the result is exception-safe code.
If T1
has a non-trivial constructors you want to use, you can just pass the arguments to make_unique<T1>
and it perfectly forwards them to the constructor of T1
.
There are issues with the multiple ways of constructing a T1
via ()
or {}
, but nothing is perfect.