Prefer to replace Pass-by-value with Pass-by-reference-to-const
In this section, let's explore the differences between value passing and reference passing.
Look at the code first:
class person{public : person (); virtual ~person (); ...... private : Std::string name; Std::string address;}; Class Student:public person{public : student (); ~student (); ...... private : Std::string schoolname; Std::string schooladdress;}; bool validatestudent (Student s); Student Plato; bool platisok=validatestudent (Plato);
We see that the argument of the Validatestudent function is that passing is the value of the pass. So what happens to the value passing, for this example, one construct and one destructor of student. There are two string objects inside it, so there are two string objects that are constructed and refactored. Student inherits from the person, plus the construction and destruction of the person, and there are two string objects inside the man, so we add 2 string objects to the construction and destruction. The total is six constructs and six destructors.
If the following code does not occur, this is a great advantage of reference delivery.
bool validateStudent(const Student &s);Student plato;bool platIsOK=validateStudent(plato);
Then there are the advantages of reference passing, and it is clear that the derived class object will not be cut.
The following code, where S is no longer the student type, but the person type, Plato's derived class part is cut in the S constructor. If it is a reference pass, the above problem will not occur, which is the polymorphism of the object.
bool validateStudent(Person s);Student plato;bool platIsOK=validateStudent(plato);
Sometimes it can be passed by value, where there are three cases of value passing, which are built-in types and STL iterators and function objects.
Effective C + + clause 20