An assignment operator that overloads an exception safe (exception safe) in its own definition class. Created a idiom of this kind. Also called: Create-temporary-and-swap.
To write robust C + + code. Exception security is important.
To be able to give abnormal safety level three:
1> Basic security: Simple to implement, low cost. Should be used as a regular means.
2> is very safe: it is not possible to achieve this step on any occasion. The assignment operator overload for this example is considered to be one.
3> does not throw an exception: can see non-throwing swap.
The so-called "Create-temporary-and-swap". is to apply for new resources first. And then released after use.
1> Use the RAII principle when applying for new resources.
2> after the successful application. Exchange resources using the non-throwing swap principle.
[CPP]View Plaincopy
- class String {
- Char * STR;
- Public:
- string& operator = (String const &s)
- {
- String temp (s); //Copy-constructor--RAII
- Temp.swap (*this); //non-throwing swap
- return *this;
- }
- void Swap (String &s) throw ()
- {
- Std::swap (this->str, s.str);
- }
- };
Sometimes it increases the inference of the number of references:
[CPP]View Plaincopy
- class String {
- Char * STR;
- Public:
- string& operator = (String const &s)
- {
- if ( This! = &s)
- String (s). Swap (*this); //Copy-constructor and non-throwing swap
- return *this;
- }
- void Swap (String &s) throw ()
- {
- Std::swap (this->str, s.str);
- }
- };
A temporary variable inside a function. can actually be omitted. Just use the pass-through method:
[CPP]View Plaincopy
- string& operator = (String s) //Pass-by-value
- {
- S.swap (*this); //non-throwing swap
- return *this;
- }
Such a practice can be optimized in some cases.
Suppose S binds to lvalue, no optimizations. Temporary objects are created inside the stack, and are assumed to be bound to rvalue. The call to copy ctor is usually omitted.
[CPP]View Plaincopy
- String createstring (); //A function that returns a String object.
- String s;
- s = createstring (); //This is an example of rvalue. An assignment operator that uses a pass-through value. can be optimized
In the c++0x standard, this assignment operator is called the "uniform assignment operator" because it combines "copy assignment" and "Move Assignment". The c++0x compiler will always optimize temporary rvalue once it discovers that a class has a move ctor present.
The old compiler certainly does not have move ctor, but is able to rvalue the assignment operation to optimize, also is a somewhat.
Copy-and-swap