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?
In general, it is perfectly safe to assign to an object that has been an argument to 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.
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).
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.
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.
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