开发者

reference front and pop_front

Is this legal?:

Sample& sample = stack.front(开发者_如何学Python);
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;


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.)


If stack based on std::deque. Exactly the same behaviour for std::vector and std::list.

From standard:

std::deque::pop_front:

Iterators and references to the erased element are invalidated. If the element is the last element in the container, the past-the-end iterator is also invalidated. Other references and iterators are not affected.


No, of course not. Once you remove the object from the collection, there's nothing your reference could refer to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜