Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference front and pop_front

Tags:

c++

stl

Is this legal?:

Sample& sample = stack.front();
stack.pop_front();

My program works. But Sample class have boost::optional<boost::posix_time::ptime> xxx member and after pop_front, is_initialized() returns false;

like image 611
userbb Avatar asked Jun 05 '11 18:06

userbb


1 Answers

No, this is not legal. You must take a copy of the object, i.e. use

Sample sample = stack.front ()

If you are using a std::vector, the pop_front call moves the elements behind to the location and your reference points to a different element (the previously second, now first element.)

like image 171
Anteru Avatar answered Oct 13 '22 02:10

Anteru