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

Suppose that there is such a function:

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 errors with std::move ? This is not only about unique_ptr , but also for other objects.

Is there any mechanism for generating an alert when we misused an object moved from ?

+7
c ++ 11 move-semantics c ++ 14
source share
3 answers

std::move a warning. If your programmers do not understand this, you should better train them. If the function is so long that the programmer can reasonably ignore the move, you need to reorganize your function to make it shorter.

+15
source share

Not every problem can or should be solved in the source code.

  • Using unique_ptr is an implementation detail; encapsulate it.

  • Indicate the conditions for preliminary and subsequent operation of the function and use tests.

0
source share

It would be nice to have compiler help, right? There are good reasons why it’s not as easy as you think:

  • std::move() not magic, and you can write a similar function. How would the compiler know that your new function should be handled the same way? You will need a standard attribute to decorate the function. If you make the warning specific to the exact function std::move , you will encode knowledge of the standard library in the language compiler.
  • Although, as a rule, a moved object can be assigned or destroyed, some classes can provide more reliable guarantees regarding the state with a transition (for example, a container can be documented as a valid empty collection when moving from). How can you tell the compiler which operations are safe for certain relocated objects?

ΒΉ Counter-argument: compilers already do something similar, of course, when checking format strings for std::printf() and std::scanf() function families.

0
source share

All Articles