Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should one use a std::move on a nullptr assignment?

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;
};
like image 526
bjackfly Avatar asked Aug 06 '13 01:08

bjackfly


People also ask

When should we use std :: move?

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.

Can std :: string be nullptr?

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 .

What does move () do?

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.

Does std :: move make a copy?

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.


2 Answers

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).

like image 175
Casey Avatar answered Sep 19 '22 18:09

Casey


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.

like image 22
Oliver Dain Avatar answered Sep 21 '22 18:09

Oliver Dain