The question is about self-assignment. For example copying a vector into itself:
std::vector<std::string> vec(5, "hello"); vec = vec;
Should the code above perform 5 assignment operations of strings into themselves, or just do nothing? I mean whether the following checking is valid:
std::vector operator=(const std::vector &rhs) { if (this == &rhs) { return *this; } ... }
I'm working on my own implementation of std::variant
class (just for fun) and interested if I should add a self-assignment check to the beginning of the assignment operator, or should I just copy the contained element into itself?
I understand that generally this doesn't matter. You should not make a class that utilizes the fact of copying into itself. But I'm interested if the standard says anything about this.
So, the conclusion, use std::unordered_set or std::unordered_map (if you need the key-value feature). And you don't need to check before doing the insertion, these are unique-key containers, they don't allow duplicates.
The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe.
The pre/post conditions of assignment of a container specified by the standard (quoting latest draft):
[tab:container.req]
r = a
Ensures: r == a.
This allows but does not mandate self assignment check.
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