I came across the following. Is there any advantage to doing a move on the nullptr? I assume it is basically assigning a zero to Node* so I am not sure if there is any advantage to do a move here. Any thoughts?
template <typename T>
struct Node
{
Node(const T& t): data(t), next(std::move(nullptr)) { }
Node(T&& t): data(std::move(t)), next(std::move(nullptr)) { }
T data;
Node* next;
};
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.
Taking a nullptr and a size in the constructor (e.g. std::string s(nullptr, 3) ) is still valid and remains undefined behaviour. These changes are also valid for string_view .
Move Constructor And Semantics: 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 actually just a request to move and if the type of the object has not a move constructor/assign-operator defined or generated the move operation will fall back to a copy.
nullptr
is by definition an rvalue (C++11 §2.14.7p1), so std::move(nullptr)
is nullptr
. It has no effect, just as would be the case for passing any other rvalue literal to std::move
, e.g., std::move(3)
or std::move(true)
.
There isn't any advantage to using std::move for any POD type, and a pointer is a POD type. std::move
allows you to move some data rather than copy it. For example, if you std::move
one std:string
into another, the pointer to the underlying storage is copied instead of the entire array being copied. But note that the pointer value is still being copied. Thus, if all you're working with is the pointer, std::move
has no advantage - it doesn't matter if that pointer is null
or not.
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