Is the following well-defined?
std::vector<std::string> v{"test"};
v.assign(1, v.at(0));
If the old sequence was destroyed before the new one is constructed
the reference passed to assign
would be invalidated and hence the
program would be ill-formed.
Does the standard mention this case (the value being part of the old sequence) or something similar anywhere, making this construct well-formed? I couldn't find anything.
From the copy of Dinkumware's standard library implementation shipped
with VS2010 (_Assign_n
is what's called internally by assign
):
void _Assign_n(size_type _Count, const _Ty& _Val)
{ // assign _Count * _Val
_Ty _Tmp = _Val; // in case _Val is in sequence
erase(begin(), end());
insert(begin(), _Count, _Tmp);
}
The comment
in case _Val is in sequence
suggests that either the standard explicitly states that assigning an element that is part of the current sequence is well-formed, or that Dinkumware's implementation just tries to be smart ;)
Which one is it?
vector:: assign() is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary.
Algorithm. Begin Initialize a vector v1 with its elements. Declare another vector v2. Call assign() to copy the elements of v1 to v2.
This is undefined behaviour, the copied element cannot come from the container itself.
[sequence.reqmts] table 84 (draft n4606)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With