Talk:More C++ Idioms/Copy-and-swap

Hi, the text after the first piece of code says: "A check for self assignment is not strictly necessary but can give some performance improvements in (rarely occurring) self-assignment cases."

I don't understand why a check for self assignment is not necessary. If we have a String s1, whose str pointer is pointing somewhere, and we write then: s1 = s1; This will: 1) create a temporary object, initialised with s1: String temp (s1);

2) swap str pointers with the current object (s1): temp.swap (s1); // so here, both temp and s1 point to the same char *.

3) return (*this)= s1:

4) delete temp, thus deleting s1.str.

So why's this acceptable?

I would have thought that one would need to write: String & operator = (String const &s) { if (this != &s) { String temp (s); // Copy-constructor -- RAII temp.swap (*this); // Non-throwing swap }     return *this; }

Can someone please explain why this is not the case?

Answer
My answer (isn't there an answer function here?): s and temp are not the same pointer (if the Copy contstructor is using deep copy).

Additional
It should use deep copy or every copy could potentially break the program, or without deleting the char pointer you would have memory leaks (if the String is destroyed). Further it might be better to use "String& operator=(String s)". It will call the copy constructor implicitly and the compiler might be able to optimize better. (stackoverflow) Further self-assignments are very very rare, in almost every case an additional check will slow down the program.

unifying assignment operator and exception specification?
Should one use the unifying assignment operator when move assignment is noexcept, copy assignment, however, might throw? --NeoUrfahraner (discuss • contribs) 06:32, 22 December 2022 (UTC)