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?)
You mean, you want to write something simpler than this line?
addCallback(std::move(std::unique_ptr<Callback>(new Callback))); // bleh.
Well, the std::move()
is superfluous as you can bind temporaries to rvalue references directly:
addCallback(std::unique_ptr<Callback>(new Callback));
Sadly, there is no std::make_unique()
but a make_unique()
is easy enough to write:
template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&& args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
... which yields
addCallback(make_unique<Callback>());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.