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?)
std::move itself does "nothing" - it has zero side effects. It just signals to the compiler that the programmer doesn't care what happens to that object any more. i.e. it gives permission to other parts of the software to move from the object, but it doesn't require that it be moved.
std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.
std::move() is a function used to convert an lvalue reference into the rvalue reference. Used to move the resources from a source object i.e. for efficient transfer of resources from one object to another. std::move() is defined in the <utility> header.
std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.
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>());
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