Why is the last assignment of a variable in a function not considered a movement?

In this code:

class X { X(const X&) { // ... } X(const X&&) { // ... } // ... }; void f() { X a; // ... X b = a; // ... code that doesn't use a } 

I understand that the last statement calls the copy constructor, not the move constructor. Assuming a is never used in f() again, can the compiler automatically optimize this statement instead of using the move constructor?

PS I know about std::move() , but I ask for automatic moving.

+3
source share
3 answers

You need to write a specification that somehow handles correctly

 void f() { X a; g(a); // stash a reference to a somewhere X b = a; // can't move from a! g2(); // use the reference stored by g } 

For the transition to be safe, you will need to prove that the following code, including all the functions that it calls, does not have direct access to a , which is impossible in the general case, because the definitions of these functions may not be available to the compiler (for example, in another unit translation).

+4
source

It is difficult / impossible for the compiler to understand that a not mentioned, except for trivial scenarios. Any external function could store a pointer or a reference to a , and any external function could rely on the specified contents of the pointer.

In a situation where external functions are not involved, I assume that optimization may be possible.

0
source

Optimization will not be completely secure without a more thorough analysis. For example, a local object can be initialized with address a and do something on it after destruction, which will happen after the last statement X b = a; .

0
source

Source: https://habr.com/ru/post/1270311/


All Articles