I'm finally getting to move my codebase to C++11, which results in mostly shorter and better code.
I find however that when I call functions with a new pointer, it's quite a bit longer than before:
void addCallback(Callback*); // Takes ownership of callback.
// ...
addCallback(new Callback); // Clear.
becomes
void addCallback(std::unique_ptr<Callback>); // No comment needed now!
// ...
addCallback(std::move(std::unique_ptr<Callback>(new Callback))); // bleh.
The proposed make_unique()
template function would only somewhat improve this.
After a little experimentation, I just wrote a helper template function for this:
template <typename T>
auto move_ptr(T *t) -> decltype(std::move(std::unique_ptr<T>(t))) {
return std::move(std::unique_ptr<T>(t));
}
// ..
addCallback(move_ptr(new Callback)); // Not bad!
and it seems to work fine - but surely I'm reinventing the wheel? (And if I'm not - are there any traps or possible errors with my move_ptr
or whatever I end up calling it?)