Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would it be a good practice to store a 'validness' state for movable objects?

Tags:

c++

I am designing a library, many of the classes are movable. Many of the movable classes are passed as arguments to functions of other classes. I am thinking how to minimize code for validation checks. The instances of the movable classes are always in a valid state after constructing, however they become invalid after being moved from.

Would it be a good practise to have a flag 'valid' that is true after constructing and becomes false after moving. The only way the object could get valid again is when a valid object is moved into it.

I'll also mention that after moving the objects do not go in a state where calling functions on them would cause undefined behavior or anything. It's just that after moving the contents are garbage.

like image 443
NFRCR Avatar asked Mar 24 '14 08:03

NFRCR


People also ask

Where can we store sensitive data in Android?

The Security library has robust security features and excellent performance, and it can provide maximum protection by using the hardware-backed key store. This library can encrypt a file and data in Shared Preferences -- Android Security Library.


1 Answers

SHOULD I, OR SHOULDN'T I?

Such a flag might be suitable for debugging purposes, but normally it's up to the developer that is using your library/code to make sure that he/she never uses your objects in a way that is quirky after they have been used from.

The whole purpose of move-constructors and move-assignments is to move the data from src to dst, which effectively makes src contain nothing but garbage, and a developer using such functionality should be aware of this.

Note: constructs that should never be ill-formed includes the assignment operator(s), one should always be able to assign new data to a moved-from object.


Since a move from an object accessed via a variable (ie. an lvalue) only happens if the developer explicitly says so 1) the developer has with such code signed an invisible contract that renders him/her responsible for any side-effects of using the object after being moved from.

Note: 1) via std::move (val), static_cast<T&&> (val), or equivalent.



THE STANDARD LIBRARY

If we look in the Standard library we see that there is no valid flag in practice, instead it is (as said) up to the developer to make sure that he doesn't use invalid constructs on a moved-from object.

like image 56
Filip Roséen - refp Avatar answered Nov 15 '22 23:11

Filip Roséen - refp