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 actual copy (Dungeon), and the return of the function is also a duplicate of the value returned by the call. These copies (replicas) are produced by the object's copy constructor , which can make pass-by-value a time-consuming operation.

The proportions are as follows:

Class Person
{
Public
Person ();
Virtual ~person ();
...
Private
String name;
string address;
};


Class Student:public Person
{
Public
Student ();
~student ();
...
Private
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 pass cost of the parameter is "one student copy constructor call, plus one student destructor call".

Is it just that simple?

Let's take a closer 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 to work.

Finally, the 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, passing a student object in by value means that the overall cost is "six constructors and six destructors".


So that's the problem? How to run it efficiently?

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


BOOL Validatestudent (const student& s);


This way of passing is much more efficient: no matter what constructors or destructors are called, no matter what new objects are created. the const in the revised parameter declaration is very important. Since the original Validatestudent accepts a student argument by value, the caller knows that they are protected and the function never changes the incoming student in any way; Validatestudent can only make changes to the copy. It is now assumed that it is necessary to declare it as a const by means of the by reference method, because if you do not do so, the caller will worry about whether Validatestudent will change the incoming student.


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


class Windowwithscrollbars:public Window
{
Public
...
void display () const;
};
All of the window objects have a name that you can get through the name function.
All forms can be displayed, and you can complete 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 form name and then displays the form.
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 a passed-by-value, all the special information that causes VVSB "is a Windowwithscrollbars object" will be cut off. In the Printnameanddisplay function, the parameter w is like a Window object regardless of the original type of the object passed in. Therefore, the always window that calls the display call within Printnameanddisplay::d Isplay, is never windowwithscrollbars::d isplay.


The way to solve the segmentation 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 form is passed in, and W shows that type.

Assuming a peek 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.

Consider, for example, the following situations:

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

There is absolutely no need, because the parameters of the internal data type do not exist in the process of construction, destruction, and replication is very fast, "value passing" and "reference passing" efficiency 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 segmentation problems (slicing
Problem).
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.