This isn't a guarantee from the standard, but as another data point, v.push_back(v[0])
is safe for LLVM's libc++.
libc++'s std::vector::push_back
calls __push_back_slow_path
when it needs to reallocate memory:
void __push_back_slow_path(_Up& __x) {
allocator_type& __a = this->__alloc();
__split_buffer<value_type, allocator_type&> __v(__recommend(size() + 1),
size(),
__a);
// Note that we construct a copy of __x before deallocating
// the existing storage or moving existing elements.
__alloc_traits::construct(__a,
_VSTD::__to_raw_pointer(__v.__end_),
_VSTD::forward<_Up>(__x));
__v.__end_++;
// Moving existing elements happens here:
__swap_out_circular_buffer(__v);
// When __v goes out of scope, __x will be invalid.
}
push_back
. Another poster noted a bug in it, that it didn't properly handle the case you describe. Nobody else, as far as I can tell, argued that this was not a bug. Not saying that's conclusive proof, just an observation. – CentoRequires:
clause and precondition in the entire Standard applies only when the function is called, and breaking them before the function returns is allowed unless it runs afoul of some other rule? Because that's the only way the Standard has been interpreted to allow this. – Sevena.insert(p,i,j)
, pre: i and j are not iterators into a. Also see [res.on.arguments]/p1/b3 that effectively says that if you dov.push_back(move(v[0]));
then it is not guaranteed to work. If you move something, the std::lib is allowed to assume what you moved is truly a prvalue. But I know of no restrictions concerningv.push_back(v[0]);
. Additionally I'm aware that all std::lib implementors work hard to make this work. – Billiardspush_back
, it's ok to pass one that you know is subject to imminent invalidation? With that limited view of the functionsRequires
aka preconditions, I could break most if not all algorithms described in the Standard. – SevenRequires:
is a pre-condition, not an invariant. – KashmirRequires:
means pre-condition, and not invariant. The pre-condition only needs to hold immediately prior to the execution of the sub-program. – Kashmir