lundi 26 février 2018

Why doesn't moving an object leave it null?

A a5(move(a1));

While after the move the member vars of a1 are set to defaults, a1 itself is not set to null. You can't do a1 == nullptr... to check if a1 is useless...

I find this odd. Is there something I'm misunderstanding here? I would think that if a1 is moved, it becomes useless, this should be indicated by setting it to null somehow. No?

The thing is that by leaving a1 in a non null state, it still can be used. There is no compiler warning or error. There is no real indication that the object is in a messed up state. if a has two member vars, an int and a dynamically alloc object, the dyn alloc object will point to nullptr but the int will have a def value (of course only if implemented right...easy to mess up). So you can

a1.getInt() and get back a number not realizing that a1 has been reset.

EDIT Added sample move c'tor

A(A&& other) : num(other.num), s(other.s){
   other.num = 0;
   other.s = nullptr;     //dyn alloc obj
}

Aucun commentaire:

Enregistrer un commentaire