Effective C + + ' ning to pass-by-reference-to-const replace Pass-by-value '

Source: Internet
Author: User

Effective C + + ' ning to pass-by-reference-to-const replace Pass-by-value '

By default, C + + passes an object to a function by value (a way that inherits from C). Unless you specify otherwise, the function parameter is the initial value of the duplicate (copy) of the actual argument, and the caller obtains a copy of the function return value. These copies (replicas) are produced by the object's copy constructor , which can make pass-by-value a time-consuming operation.

Examples are as follows:

Class Person
Person ();
Virtual ~person ();
String name;
string address;

Class Student:public Person
Student ();
~student ();
String Schoolname;
String schooladdress;

Then look at the following code:

BOOL Validatestudent (Student s);//Declare a function, function to accept students by value

Student Stu; The object of the Stu class

BOOL Stuisok=validatestudent (STU);

What happens when the above function is called?

First, the copy constructor of student is called, and the S is initialized with Stu as a blueprint. When the function call is complete, s will be destroyed. Therefore, for the above function, the cost of passing the parameter is "one time student copy constructor call, plus one student destructor call".

Is it just that simple?

Let's take a concrete look at exactly what this function call does:

There are two string objects within the student object, so two string objects are constructed each time a student object is constructed.

In addition, the student object inherits from the person object, so a person object must be constructed each time the student object is constructed.

A person object also has two string objects in it, so each person construction action takes two string constructs.

The end result is: A student copy constructor, a person copy constructor, and a four-time string copy constructor are called.
When the student copy inside the function is destroyed, each constructor call action requires a corresponding destructor call action.

Therefore, a student object is passed in by value, and the overall cost is "six constructors and six destructors".

So that's the problem? How to execute efficiently?

The efficient approach is to use pass by Reference-to-const:

BOOL Validatestudent (const student& s);

This method of delivery is much more efficient: No constructors or destructors are called because no new objects are created. It is important to revise the const in this parameter declaration. Because the original validatestudent accepts a student parameter as by value, the caller knows that they are protected and never changes the incoming student in the function; Validatestudent can only modify the copy Now, if passed by reference, it is necessary to declare it as const, because if you do not do so, the caller will worry that validatestudent will not change the incoming student.

Other than thatpassing parameters by reference can also avoid slicing (object cutting) problems, let's take a look at the following example:
class Window
String name () const;
virtual void display () const;

class Windowwithscrollbars:public Window
void display () const;
All window objects have a name that you can get through the name function.
All the Windows can be displayed and you can do it through the display function.
Display is a virtual function, which means that the simplicity of the base class Window object is displayed in a different way than the ornate and noble Windowwithscrollbars object.

Now we write a function that prints the window name and then displays the window.
void Printnameanddisplay (Window w)//by value
cout << w.name () << Endl;
W.display ();
We now pass a Windowwithscrollbars object to the function:
Windowwithscrollbars WWSB;
Printnameanddisplay (WWSB);
Because it is passed-by-value, all the special information that causes VVSB "to be a Windowwithscrollbars object" is removed. In the Printnameanddisplay function, the parameter w is like a Window object, regardless of the original type of the object passed over. Therefore, the always window that calls the display call within Printnameanddisplay::d Isplay, is never windowwithscrollbars::d isplay.

The way to solve the cutting problem is to pass W by Reference-to-const;
void Printnameanddisplay(const Window &W)//by Reference
cout << w.name () << Endl;
W.display ();

now, what type of window is passed in and W shows that type.

If you look at the bottom of the C + + compiler, reference is often implemented as pointers, so pass by reference usually means a pointer is actually passed. For built-in types, pass-by-value tend to be more efficient than pass by reference.

But consider the following scenario:

should void func (int x) be rewritten as void func (const int &x) to improve efficiency?

It is completely unnecessary, because the parameters of the internal data type do not have the process of construction, destruction, and replication is very fast, and the efficiency of "value passing" and "reference passing" is almost equal.

Please remember:
1. 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
2. The above rules are not suitable for use with built-in types, as well as for STL iterators and function objects. For them, pass-by-value tend to be more suitable.

Effective C + + ' ning to pass-by-reference-to-const replace Pass-by-value '

Related Article

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.