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?
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
.]
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)
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=
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.
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