Artavo
Artavo

Reputation: 313

Is it safe to assign a container using its own iterators?

As an example:

string s = "123";
s.assign(find(s.begin(),s.end(),'2'), s.end());

Is the behavior of the above code defined? Or it leads to undefined behavior?

Upvotes: 10

Views: 131

Answers (1)

AProgrammer
AProgrammer

Reputation: 52274

Yes. This version of assign is defined as

template<class InputIterator>
  constexpr basic_string& assign(InputIterator first, InputIterator last);

Constraints: InputIterator is a type that qualifies as an input iterator.

Effects: Equivalent to: return assign(basic_­string(first, last, get_­allocator()));

which shows a temporary computed before changes taking place.

Upvotes: 5

Related Questions