By default, C ++ uses the by Value Method to pass objects to functions. The real parameters of a function are all based on the response of the actual parameter as the initial value, and the call end obtains a replica of the function return value. These copies are produced by the object's copy constructor, which may make pass by value an expensive operation.
Consider the following inheritance system:
Classperson {
Public:
Person ();
Vitual ~ Person ();
PRIVATE:
STD: stringname;
STD: stringaddress;
};
Classstudent: publicperson {
Public:
Student ();
Virtual ~ Student ();
PRIVATE:
STD: stringschoolname;
STD: stringschooladdress;
};
Now there is a function validatestudent called. Do you want to call a student real parameter and return whether it is valid?
Boolvalidatestudent (students );
Studentplato;
Boolplatoisok = validatestudent (Plato );
What happens when the above call occurs? We use graphs to illustrate:
Is it over? That's not the case. Check again.
We know that the student class inherits the person class, and both classes have variables of the string class type. My God
If there is a method that can circumvent all of these constructor and destructor, that's fine.
Yes, that is, pass by reference to const.
Boolvalidatestudent (conststudent & S );
Note that this method is also used to prevent objects from being cut.
Voidprintstudent (personp ){
Cout <schoolaname <Endl; // error,
}
...
Studentplato;
Printstudent (Plato); // The name was originally intended to be printed, but a problem may occur because the object is cut.
Why can we avoid being cut after being referenced?
If you peat the C ++ underlying layer, you will find that the reference is usually implemented by pointers. Therefore, the passed pointer.
If your parameter is of a built-in type, using pass by value is more efficient than using pass by reference to const.
Remember:
L try to replace pass by value with pass by reference to const. The former is usually relatively efficient and can avoid cutting problems.
L The above rules are not applicable to built-in types, as well as STL iterators and function objects. For them, pass by value is more appropriate.