Replace pass-by-value (prefer pass-by-conference-to-const) with pass-by-reference-to-Const.
To pass-by-value .)
Pass-by-conference-to-const:
ClassPoint
{
Public:
Point(): Xval (2), yval (2 ){Printf("% D, % d/N", xval, yval );}
Void Setxval(IntI) {xval = I ;}
Private:
IntXval, yval;
};
Void Const_test(ConstPoint * P)
{
P-> setxval (9 );
}
Point * P =NewPoint ();
Const_test (P );
This will cause compilation errors:
"Error: Use 'const point' as 'void point: setxval (INT )'
The Type limit is discarded when the 'eas' parameter"
That is to say, "const
Point * P ", P members cannot be changed.
Similarly, Point member functions:
Void Setxval(Int
I) const {xval = I ;}
This will also cause compilation errors, because in the setxval function, this is a const. Const modifies conference.
Pass-by-Value:
Void Const_test(Point P)
{
}
Point P;
Const_test (P );
In this way, a copy constructor call is involved from P to function arguments.
Pass-by-conference-to-constAdvantages:
1,
No constructor or destructor is called.
2,
Slicing can be avoided: When a derived class is passed by-value and is considered as a base class object, the base class constructor copy constructor can be called, in this way, the derived class part of the new object will be discarded and a base class object will be obtained. In this way, calling the virtual function will call the base class instead of the expected derived.
3,
For built-in type objects, STL iterators, function objects, pass
By-value is usually better than pass-by-reference-to-Const.
High efficiency. Otherwise, replace pass-by-reference-to-const with pass-by-value.
Note:
1,
Use pass-by-reference-to-const instead of pass-by-value. The former is usually relatively efficient and can avoid slicing problems.
2,
The preceding rules do not apply to built-in type objects, STL iterators, and function objects. For them, pass-by-value is usually appropriate.