Effective C + + clause 20: Prefer to replace pass-by-value with Pass-by-reference-to-const

Source: Internet
Author: User

Remember:

    • Replace Pass-by-value with Pass-by-reference-to-const as much as possible. The former is usually more efficient and avoids cutting problems (slicing problem).
    • The above rules do not apply to built-in types, as well as STL iterators and function objects. For them, pass-by-value tend to be more appropriate.
classPerson { Public: Person (); Virtual~Person (); ...Private:    stringname; stringaddress;};classStudent: PublicPerson { Public: Student (); ~Student (); ...Private:    stringSchoolname; stringschooladdress; };BOOLvalidatestudent (Student s); Student Plato;BOOLPlatoisok =Validatestudent (Plato);//One-time student copy constructor//one-time person copy constructor//two string copy constructors in student//two string copy constructors in person//the corresponding six-second destructor uBOOLValidatestudent (Conststudent&s);//so there is no copy of the constructor and destructor calls.

classWindow { Public:    ...    stringName ()Const; Virtual voidDisplay ()Const;};classWindowwithscrollbars: PublicWindow { Public:    ...    Virtual voidDisplay ()Const;};voidPrintnameanddisplay (Window W)//Not right!{cout<<W.name (); W.display ();}//The parameter w is constructed as a Windows object, and the unique information for the Windowswithscrollbars object is lost. //so always call window::d isplay//SolutionsvoidPrintnameanddisplay (Constwindow&W) {cout<<W.name (); W.display ();}

Effective C + + clause 20: Prefer to replace pass-by-value with Pass-by-reference-to-const

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.