Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector.assign() with value in sequence

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?

like image 860
Max Truxa Avatar asked Aug 24 '16 12:08

Max Truxa


People also ask

Can we assign a value to a vector?

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.

How do you assign one vector to a v1 to v2?

Algorithm. Begin Initialize a vector v1 with its elements. Declare another vector v2. Call assign() to copy the elements of v1 to v2.


1 Answers

This is undefined behaviour, the copied element cannot come from the container itself.

[sequence.reqmts] table 84 (draft n4606)

enter image description here

like image 51
user657267 Avatar answered Oct 13 '22 13:10

user657267