Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes. There are two common options. One - which is generally discouraged - is to call the <code>operator=</code> from the copy constructor explicitly:</p> <pre><code>MyClass(const MyClass&amp; other) { operator=(other); } </code></pre> <p>However, providing a good <code>operator=</code> is a challenge when it comes to dealing with the old state and issues arising from self assignment. Also, all members and bases get default initialized first even if they are to be assigned to from <code>other</code>. This may not even be valid for all members and bases and even where it is valid it is semantically redundant and may be practically expensive.</p> <p>An increasingly popular solution is to implement <code>operator=</code> using the copy constructor and a swap method.</p> <pre><code>MyClass&amp; operator=(const MyClass&amp; other) { MyClass tmp(other); swap(tmp); return *this; } </code></pre> <p>or even:</p> <pre><code>MyClass&amp; operator=(MyClass other) { swap(other); return *this; } </code></pre> <p>A <code>swap</code> function is typically simple to write as it just swaps the ownership of the internals and doesn't have to clean up existing state or allocate new resources.</p> <p>Advantages of the copy and swap idiom is that it is automatically self-assignment safe and - providing that the swap operation is no-throw - is also strongly exception safe.</p> <p>To be strongly exception safe, a 'hand' written assignment operator typically has to allocate a copy of the new resources before de-allocating the assignee's old resources so that if an exception occurs allocating the new resources, the old state can still be returned to. All this comes for free with copy-and-swap but is typically more complex, and hence error prone, to do from scratch.</p> <p>The one thing to be careful of is to make sure that the swap method is a true swap, and not the default <code>std::swap</code> which uses the copy constructor and assignment operator itself.</p> <p>Typically a memberwise <code>swap</code> is used. <code>std::swap</code> works and is 'no-throw' guaranteed with all basic types and pointer types. Most smart pointers can also be swapped with a no-throw guarantee.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload