Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range-based loop, unique pointers, and move semantics

Here is the a code similar to one I have:

for (auto &uptr : vector_of_unique_ptrs) {              // 1
  auto result = do_the_job_with_pointee(uptr.get());    // 2
  record_intermidiate_result(result, std::move(uptr));  // 3
}

Here I have a vector of unique pointers to some objects (line 1).

I iterate over the vector (line 1) and do some work using the pointee (line 2).

After the job is done I need to take a result and pass the ownership to some other place (line 3).

The code compiles and executes without any problems, but I have feeling that it's not legal to move iteratee during iteration.

I "skimmed" though publicly available C++11 draft, but didn't find any clarifications on the subject.

Could anybody tell me is the code above legal or not?

like image 680
AlexDenisov Avatar asked Dec 03 '22 14:12

AlexDenisov


1 Answers

Your code is absolutely legal and well-defined. Nothing prevents you from modifying elements of the sequence during iteration, and moving is just a form of modification.

Just keep in mind to not try to use those pointers after the loop.

like image 53
SergeyA Avatar answered Dec 20 '22 09:12

SergeyA