Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to reset std::list after been moved?

Tags:

c++

c++11

I've got following code:

std::list some_data;
...
std::list new_data = std::move(some_data);
some_data.clear();
...

The question is whether some_data.clear() is necessary? (for the record, some_data will be reused in the future)

like image 814
ji chengde Avatar asked Oct 08 '18 07:10

ji chengde


People also ask

Is std :: move necessary?

A: You should use std::move if you want to call functions that support move semantics with an argument which is not an rvalue (temporary expression).

What happens when you move a vector?

Note that moving the vector around doesn't change the vector, as the position of the vector doesn't affect the magnitude or the direction. But if you stretch or turn the vector by moving just its head or its tail, the magnitude or direction will change.

Can I use variable after std :: move?

You must not use a variable after calling std::move() on it. Since you have casted your variable to an rvalue, functions that receive rvalues may act destructively on your variable, so using the variable's contents afterward may result in undefined behaviour.

Can I use object after std :: move?

In general, it is perfectly safe to assign to an object that has been an argument to std::move .


1 Answers

Yes, it's necessary.

Only the std smart pointers are guaranteed to be in a default constructed state after being moved from.

Containers are in an valid, but unspecified state. This means you can only call member functions without preconditions, e.g. clear, that put the object in a fully known state.

like image 155
rubenvb Avatar answered Sep 21 '22 19:09

rubenvb