Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::move- How to warn programmer not to use *moved from* object

Suppose there is a function like this:

int * func()
{
  std::unique_ptr<int> ptr(new int(3));
  //Few more lines of code

  //then one function added where programmer writes like some thing

  SOME_OTHER_FUNC(std::move(ptr));

  return ptr.get();
}



void SOME_OTHER_FUNC(std::unique_ptr<int> arg_ptr)
{
}

Is there a way to warn programmers to avoid such mistakes with std::move? This is not about unique_ptr only but for other objects too.

Is there any mechanism to generate a warning when we used a moved-from object inappropriately?

like image 249
gaurav bharadwaj Avatar asked Oct 05 '16 14:10

gaurav bharadwaj


People also ask

Can I use the object after std :: move?

In general, it is perfectly safe to assign to an object that has been an argument to std::move .

What does std :: move () do?

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.

Should you use std :: move?

Q: When should it be used? A: You should use std::move if you want to call functions that support move semantics with an argument which is not an rvalue (temporary expression).

What is the difference between Move and Copy C++?

Move constructor moves the resources in the heap, i.e., unlike copy constructors which copy the data of the existing object and assigning it to the new object move constructor just makes the pointer of the declared object to point to the data of temporary object and nulls out the pointer of the temporary objects.


1 Answers

std::move is the warning. If your programmers don't understand this, you have to educate them better. If the function is so long that the programmer can reasonably overlook the move, you need to refactor your function to make it shorter.

like image 87
Sebastian Redl Avatar answered Nov 07 '22 11:11

Sebastian Redl