Is stl container safe to assign?

For instance:

set<int> s1;
set<int> s2;
s1.insert(1);
s2.insert(2);
s1 = s2;

It is safe? If so, where did the old element (and memory) come from?

+5
source share
4 answers

Yes, it’s safe to complete the task. It calls the copy constructor or assignment operator, and old elements are erased in s1and replaced by elements s2.

[Note. If there was any potential problem, the constructor and copy assignment would have been banned as fstream, ofstream, ifstream.]

+6
source

. , . (, , , , )

+5

, . : s2 s1, s2 s1. . : set:: operator =

+4

.

, s1, ( no-op int ). , , .

New objects in s1 will be copied from those in s2, which can take considerable time. If you do not want to save s2 after the assignment, it is better to use swap for two containers or use the C ++ 11 move destination.

std::swap(s1, s2);  // Backwards-compatible swap
s1 = std::move(s2); // C++11 rvalue move assignment

Both of them, most likely, will simply change one pointer, leaving the contents that you want to save in s1, and the rest in s2, which will be cleared when s2 is out of scope.

0
source

All Articles