Why You Should Only Rarely Use std::move -- Andreas Fertig

andreas-fertig.pngstd::move can allow the efficient transfer of resources from object to to object. Andreas Fertig reminds us that using std::move inappropriately can make code less efficient.

Why You Should Only Rarely Use std::move

by Andreas Fertig

From the article:

The example in Listing 1 is the code I used to make my point: don’t use std::move on temporaries! Plus, in general, trust the compiler and only use std::move rarely. For this article, let’s focus on the example code.

class S {
public:
  S() { printf("default constructor\n"); }
  ~S() { printf("deconstructor\n"); }
  // Copy constructor ①
  S(const S&) { printf("copy constructor\n"); }
  // Move constructor ②
  S(S&&) { printf("move constructor\n"); }
};
void Use()
{
  S obj{
    S{} // Creating obj with a temporary of S ③
  };
}
Listing 1

Here we see a, well, perfectly movable class. I left the assignment operations out. They are not relevant. Aside from the constructor and destructor, we see in ① the copy constructor and in ② the move constructor. All special members print a message to identify them when they are called.

Further down in Use, we see ③, a temporary object of S used to initialize obj, also of type S. This is the typical situation where move semantics excels over a copy (assuming the class in question has movable members). The output I expect, and I wanted to show my participants, is:

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.