Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it safe to assign a stl container?

For example:

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

Is it safe? If so, where did the old element(and the memory they occurred) come to?

like image 385
Lai Yu-Hsuan Avatar asked Jun 20 '12 16:06

Lai Yu-Hsuan


4 Answers

Yes it's safe to do the assignment. It calls the copy constructor or assignment operator and the older elements are erased in s1 and are replaced by the elements of s2.

[Note: If there would have been any potential problem then copy constructor and assignment would have been forbidden like fstream, ofstream, ifstream.]

like image 173
iammilind Avatar answered Sep 25 '22 12:09

iammilind


Yes. The old elements will be destroyed in the usual way and any memory freed. (Of course as usual if you store pointers in the container it will only destroy the pointer, and won't free the thing it points to)

like image 31
jcoder Avatar answered Sep 21 '22 12:09

jcoder


Yes your examples is safe. But note: You don't assign s2 to s1, you copy s2 to s1. For further information see this: set::operator=

like image 36
Lukas Schmelzeisen Avatar answered Sep 23 '22 12:09

Lukas Schmelzeisen


The assignment is safe.

The assignment operator will destroy the objects originally contained in s1 by calling their destructor (a trivial no-op for the int in your example). Whether the set frees the memory as well, or retains it as uninitialized memory for use by subsequently added elements, is up to the implementation.

The new objects in s1 will be copied from those in s2, which might take considerable time. In case you don't want to keep s2 around after the assignment, better approaches might be to swap the two containers or to use the C++11 move assignment.

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

Both of these will most likely just swap a single pointer, leaving the content you want to keep in s1 and the rest in s2, to be cleared when s2 goes out of scope.

like image 26
MvG Avatar answered Sep 23 '22 12:09

MvG