Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should an STL container avoid copying elements into themselves when the container is copied into itself?

Tags:

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.

like image 291
anton_rh Avatar asked Aug 27 '19 10:08

anton_rh


People also ask

Which containers do not allow duplicates?

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.

Is STL container thread safe?

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.


1 Answers

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.

like image 157
eerorika Avatar answered Oct 26 '22 06:10

eerorika