Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to mechanically identify which operations are safe on a moved-from object?

Moveability allows a great class of optimizations. Yet, it feels that it does this at the cost of punching a hole in the static safety of programs:

After a move, the source object is left in a valid but unspecified state, where some operations are legal, but some are not. (notably see this SO question for discussions around this topic). It would seem that this list of operations, even though it is dependent on each type, can be known at compile time. Yet, the compiler does not warn about incorrect uses of moved-from objects (as this other SO question discusses).

It felt like C++ philosophy to rely on the compiler to validate as much as possible (of what is statically known), one of many example being const-correctness enforcement. Yet, it seems that moved-from object can be used in dangerous ways, without the compiler making attempts (or having any mean) to catch them.

Is there actually a mechanism allowing better diagnostic from the compiler ? If not, why is not there a new qualifier to apply to methods that can be used on a moved from object, or another mechanism allowing equivalent static verifications ?

like image 855
Ad N Avatar asked Oct 16 '15 09:10

Ad N


2 Answers

Moveability allows a great class of optimizations. Yet, it feels that it does this at the cost of punching a hole in the static safety of programs.

Yes, it does.

It would seem that this list of operations, even though it is dependent on each type, can be known at compile time.

But not by the compiler, in general.

Yet, the compiler does not warn about incorrect uses of moved-from objects.

It would be nice, though!

Nope, you're going to have to rely on the documentation. Or just do what I do and, having moved from an lvalue, never use that object again unless you have a tightly controlled scope and some obvious "reset" operation on the object immediately thereafter.

Of course, moving from an rvalue doesn't exhibit this problem.

like image 71
Lightness Races in Orbit Avatar answered Nov 15 '22 18:11

Lightness Races in Orbit


I think it's unlikely that some additional qualifier will be added to the standard for an edge case like this.

One possibility would be to mark your function declarations with #pragma supports_moved_from or something, then build a static-analysis tool to detect calls to functions on potentially moved-from objects and check if they were marked.

You could probably use one of the many Clang tool interfaces for this.

like image 31
TartanLlama Avatar answered Nov 15 '22 17:11

TartanLlama