Before designing a class, you must first determine whether the object instantiated by the class is the value semantics or the reference semantics. Value Semantics
It is generally used for non-dedicated resource objects,
Indicates that the object can be like int
In the same way, you can copy and re-assign values without causing resource leakage or cutting (that is, some resources are released and some are leaked ). Reference semantics is generally used for dedicated resource encapsulation.
Object
Indicates that the object cannot be copied or re-assigned. In terms of syntax,
The following code is valid for the value semantics and invalid for the reference Semantics
:
Cmyobject A, C;
Cmyobject B ();
// The value semantics is valid, and the reference semantics is invalid.
C = A; // The value semantics is valid, and the reference semantics is invalid.
Note: If the preceding statements are valid and executed successfully
When the status of object a changes, the syntax of the object class is represented by the value semantics, but the reference semantics is essentially. For example
STD: autoptr
.
Reference semantics and
Value semantics Application
The basic rules are as follows:
:
1. Try to make the object realize the value semantics instead of the reference semantics. Reference semantic objects cannot be used in
STL
Container.
2,
To System
Dedicated
Classes encapsulated by resources
Available
Reference semantics. Such as printer encapsulation and screen desktop.
3. definition reference semantics displayed by declaring without defining the copy constructor and value assignment operator.
4. Using the reference counting technology, you can implement a reference semantic object as a value semantic object.
5. base class objects should disable value semantics, but provide
Clone
Method To copy objects.
Syntax for referencing semantics is implemented as follows:
Class cmyobject
{
Public:
Typedef cmyobjectmy_type;
...
Public:
// Copy the constructor
(
Declare but not define, disable value Semantics
)
Cmyobject (const my_type & RHs );
// Overload the value assignment operator
(
Declare but not define, disable value Semantics
)
My_type & operator = (const my_type & RHs );
....
};
The syntax of value semantics is as follows:
Class cmyobject
{
Public:
Typedef cmyobject
My_type;
...
Public:
// Copy the constructor
Cmyobject (const my_type & RHs ){...}
// Overload the value assignment operator
(
Declare but not define, disable value Semantics
)
My_type & operator = (const my_type & RHs)
{
My_type atemp (RHA );
Swap (atemp );
}
Void swap (my_type & RHs ){...}
....
};
Hu leqiu
2010/8/3 in Changsha
Http://blog.csdn.net/hlqyq