Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c++ > #87128

Re: Is Copy-and-swap idiom too slow in assignment operator?

From Andrey Tarasevich <andreytarasevich@hotmail.com>
Newsgroups comp.lang.c++
Subject Re: Is Copy-and-swap idiom too slow in assignment operator?
Date 2022-10-22 02:16 -0700
Organization A noiseless patient Spider
Message-ID <tj0ce8$spig$1@dont-email.me> (permalink)
References <tj0448$rtfp$3@dont-email.me>

Show all headers | View raw


On 10/21/2022 11:55 PM, JiiPee 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;
> ...

With what kind of class? What is `a` and `b`?

If this is a flat class, then of course straightforward copying will be 
faster, since it requires only one copying, while copy-and-swap will 
copy the same data twice (or even thrice). The larger the class - the 
slower in comparison the copy-and-swap is going to be.

If this is a "deep" class that handles resources, which need to be 
copied, then in general case expenses spent on releasing the old 
resources and cloning new ones in copy constructor or assignment 
operator will dwarf the overhead brought in by swapping.

-- 
Best regards,
Andrey.

Back to comp.lang.c++ | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


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