Effective C + + clause 20

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.