473,611 Members | 2,236 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

using swap to make assignment operator exception safe

Hello everyone,
The following swap technique is used to make assignment operator
exception safe (means even if there is exception, the current object
instance's state is invariant).

It used a temporary object "temp" in this sample, and assignment is
made on a to temp ar first. Even if there is exception, the current
this object's state is not corrupted.

My question is, the pattern works only if there is no exception thrown
by swap function. If there are exception in swap function, the state
of current object instance may still be corrupted (swap may invoke the
assignment operator of member variables). Is my understanding correct?

Expand|Select|Wrap|Line Numbers
  1. class A;
  2. A& A::operator= (const A& a)
  3. {
  4. A temp;
  5. temp = a; // exception may be thrown
  6. swap (*this, temp);
  7. return *this;
  8. }
  9.  

thanks in advance,
George
Jan 8 '08 #1
4 3275
George2 wrote:
Hello everyone,
The following swap technique is used to make assignment operator
exception safe (means even if there is exception, the current object
instance's state is invariant).

It used a temporary object "temp" in this sample, and assignment is
made on a to temp ar first. Even if there is exception, the current
this object's state is not corrupted.

My question is, the pattern works only if there is no exception thrown
by swap function. If there are exception in swap function, the state
of current object instance may still be corrupted (swap may invoke the
assignment operator of member variables). Is my understanding correct?
[snip]

Yes.

Note, however, that swap does not throw for built-in types and for standard
containers. Moreover, given a class

class SomeClass {

type_1 member_1;
type_2 member_2;
...

};

the obvious implementation of swap is

swap ( SomeClass & lhs, SomeClass & rhs ) {
swap( lhs.member_1, rhs.member_1 );
swap( lhs.member_2, rhs.member_2 );
...
}

And this implementation will not throw provided that the swap functions for
type_1, type_2, ... do not throw. Thus, in principle, swap could be
implemented as a no-throw operation for all types.

However, there is a catch: libraries and other code outside your control. If
type_3 is defined in some third-party library and does not provide a
no-throw swap, the argument breaks down and you might have to work around
the problems.

(Since the code for swap conforms to a uniform pattern, one has to wonder if
it would be a good idea to change the language so that the compiler will
generate a default swap function for each type very much like the compiler
provided copy-constructor and assignment operator.)
Best

Kai-Uwe Bux
Jan 8 '08 #2
George2 wrote:
>
Expand|Select|Wrap|Line Numbers
  1. class A;
  2. A& A::operator= (const A& a)
  3. {
  4.     A temp;
  5.     temp = a; // exception may be thrown
  6.     swap (*this, temp);
  7.     return *this;
  8. }
  9.  

The above code loops infinitely. The "temp = a"
line calls the assignment operator again.

The idiom you want is:

A& A::operator=( const T& other )
{
A temp( other );
swap(*this, temp );
return *this;
}

Your assumptions are wrong. The code is safe
regardless whether A's copy constructor or swap
throws exceptions as long as they are internally
exception safe.

Jan 8 '08 #3
On Jan 8, 2:53 pm, Ron Natalie <r...@spamcop.n etwrote:
George2 wrote:
Expand|Select|Wrap|Line Numbers
  1.  class A;
  2.  A& A::operator= (const A& a)
  3.  {
  4.      A temp;
  5.      temp = a; // exception may be thrown
  6.      swap (*this, temp);
  7.      return *this;
  8.  }
  9.  

The above code loops infinitely. The "temp = a"
line calls the assignment operator again.

The idiom you want is:

A& A::operator=( const T& other )
{
A temp( other );
swap(*this, temp );
return *this;
}

Your assumptions are wrong. The code is safe
regardless whether A's copy constructor or swap
throws exceptions as long as they are internally
exception safe.
swap() should never throw any exceptions.

Probably he wanted to write:
A temp = a; // exception may be thrown
Jan 8 '08 #4
Ron Natalie wrote:
The idiom you want is:

A& A::operator=( const T& other )
{
A temp( other );
swap(*this, temp );
return *this;
}
I prefer the shoter version:
A& A::operator=(A src)
{
swap(*this, src);
return *this;
}

Should be semantically equivalent to your version.

--
Dizzy

Jan 8 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
7826
by: Davis King | last post by:
Can I assume that std::swap will not throw when it is used to swap std::string objects? In the standard it says that the swap() std::string member function runs in constant time. I didn't see anything that said that swapping strings was guaranteed to not throw though. But it would seem that a constant time swap ought not to throw though. I can't really see a way to implement one that does throw without deliberately sabotaging it at...
10
2261
by: Tony Johansson | last post by:
Hello Experts!! This class template and main works perfectly fine. I have this class template called Handle that has a pointer declared as T* body; As you can see I have a reference counter in the class template so I know how many references I have to the body. In my case it's the Integer wrapper class which is the body. This template works for many different types. The one that I use is named Integer and is a Wrapper for an int. The...
16
3254
by: Martin Jørgensen | last post by:
Hi, I've made a program from numerical recipes. Looks like I'm not allowed to distribute the source code from numerical recipes but it shouldn't even be necessary to do that. My problem is that I'm not very experienced with pointers, pointers to pointers and the like and I got 4 compiler warnings + I don't completely understand how to build this "compact matrix" (see later).
6
11586
by: Jack White | last post by:
Does anyone know if an analogue to the "swap()" function found in C++ exists in C#. For those not familiar, let's say you have a function that loads some collection passed in by reference. If an error occurs while loading then the collection will be in an indeterminate state. The work-around in C++ is to load a temporary collection first and once successful, invoke a (native) "swap()" function to exchange each object's internal "handle" to...
1
2096
by: ma740988 | last post by:
Consider the source snippet. # include <iostream> struct foo_struct { int odx ; int pdx ; foo_struct () : odx ( 0 ) , pdx ( 0 )
28
2836
by: Jess | last post by:
Hello, It is said that if I implement a "swap" member function, then it should never throw any exception. However, if I implement "swap" non- member function, then the restriction doesn't apply. Can somebody tell me why? Thanks, Jess
5
1426
by: Weihui Shen | last post by:
Hello. Sometimes I see that some class constructors were implemented with assignment operator and I wanna know whether it is safe to do that or not?
16
1926
by: George2 | last post by:
Hello everyone, The following swap technique is used to make assignment operator exception safe (means even if there is exception, the current object instance's state is invariant). It used a temporary object "temp" in this sample, and assignment is made on a to temp ar first. Even if there is exception, the current this object's state is not corrupted. My question is, the pattern works only if there is no exception thrown by swap...
14
1758
by: KK | last post by:
Dear All I have a small problem with using as operator on value type array. Here is an example what I am trying to do. using System; using System.Collections.Generic; using System.Text;
0
8596
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8240
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8411
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6072
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5527
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4042
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2546
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1692
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1411
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.