Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c++ > #87151
| From | Juha Nieminen <nospam@thanks.invalid> |
|---|---|
| Newsgroups | comp.lang.c++ |
| Subject | Re: Is Copy-and-swap idiom too slow in assignment operator? |
| Date | 2022-10-24 07:10 +0000 |
| Organization | Aioe.org NNTP Server |
| Message-ID | <tj5dop$ccr$1@gioia.aioe.org> (permalink) |
| References | <tj0448$rtfp$3@dont-email.me> |
JiiPee <kerrttuPoistaTama11@gmail.com> wrote: > In a class when defining an assignment operator: > > operator=(const Obj& other) > > , if one uses the Copy-and-swap idiom to copy @other to this: > > Obj copy(other); > copy.swap(*this); > > , this is obviously really good looking and elegant etc. But just > wondering how much slower it would be than a straight/old (not so > elegant/risky): > > this->a = other.a; > this->b = other.b; > ... It depends on the situation. For example, suppose you are assigning one (object similar to) std::string to another: If the target already has enough capacity to contain the source string, then no new allocations will be needed and it's just a simple straightforward string copy. If the copy-and-swap idiom had been used here, a new dynamic memory allocation would have been done and the existing one would have been deleted, for no good reason. The difference becomes even more drastic with classes like std::list (or any class with a similar functionality): If the target already has elements in it, then assigning can just assign the source elements onto the existing target elements, thus avoiding unneeded extra allocations. The copy-and-swap idiom would make dynamic allocations for every single element to be copied, and then delete the existing ones, for no reason. Of course in other situations it doesn't really make much of a difference.
Back to comp.lang.c++ | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Is Copy-and-swap idiom too slow in assignment operator? JiiPee <kerrttuPoistaTama11@gmail.com> - 2022-10-22 09:55 +0300
Re: Is Copy-and-swap idiom too slow in assignment operator? Andrey Tarasevich <andreytarasevich@hotmail.com> - 2022-10-22 02:16 -0700
Re: Is Copy-and-swap idiom too slow in assignment operator? Sam <sam@email-scan.com> - 2022-10-22 07:50 -0400
Re: Is Copy-and-swap idiom too slow in assignment operator? JiiPee <kerrttuPoistaTama11@gmail.com> - 2022-10-22 16:02 +0300
Re: Is Copy-and-swap idiom too slow in assignment operator? Juha Nieminen <nospam@thanks.invalid> - 2022-10-24 07:10 +0000
Re: Is Copy-and-swap idiom too slow in assignment operator? JiiPee <kerrttuPoistaTama11@gmail.com> - 2022-10-24 17:38 +0300
Re: Is Copy-and-swap idiom too slow in assignment operator? Öö Tiib <ootiib@hot.ee> - 2022-10-29 11:59 -0700
csiph-web