Value Transfer and reference transfer of C ++, value transfer reference

Source: Internet
Author: User

Value Transfer and reference transfer of C ++, value transfer reference

1 Value Transfer

The value transfer is actually,Copy the value of a real ParameterPassed to the form parameter, often used in "small object" (small objects)

int fact(int val) // factorial of val {    int ret = 1;        // assign ret * val to ret and decrement val    while (val > 1)        ret *= val--;         return ret;}

Call this function:

cout << "5! is " << fact(5) << endl;

<Valid tive C ++>:Built-in type (built-in types), STL iterator, function object type (function object types)

 

2 reference Transfer

The reference transfer does not involve copying. What is passed to the parameter isReference of Real VariableIt is often used to pass "large value" (large values)

There are two advantages of using reference transfer: more efficient and anti-disconnection

2.1 more efficient

The following is the definition of the Person base class and its derived class Student.

// class Person and its subclass Studentclass 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;};

There is a function that verifies the identity of a student. If the form parameter is passed as a value, the cost of copying the real parameter to the form parameter is: The base class Person constructor is called once, the constructor of the string type data member in the base class twice,

The Student constructor of the derived class is one time. The string type data member in the derived class is two times, and the corresponding destructor is also called six times, for a total of 12 calls, which is naturally inefficient.

The use of reference transfer does not involve the copy operation, which significantly improves the efficiency.

// 1) pass-by-value bool validateStudent(Student s);// 2) pass-by-reference-to-const bool validateStudent(const Student& s);

2.2 anti-disconnection

In the following example, In the derived class javaswwithscrollbars, the virtual function display of the base class Window is rewritten.

// base class Window
class Window{public: std::string name() const; // return name of window virtual void display() const; // draw window and contents};class WindowWithScrollBars : public Window {public: virtual void display() const;};

In the printNameAndDisplay function, the dispaly function is called. If the parameter is passed by value, "slicing" will occur, that is, wwsb calls Window: display ()

// pass-by-value is incorrectvoid printNameAndDisplay(Window w){    std::cout << w.name();    w.display();}// WindowWithScrollBars object will be sliced offWindowWithScrollBars  wwsb;printNameAndDisplay(wwsb);

In printNameAndDisplay, the passed parameters are not modified. Therefore, pass-by-const-reference can be used to avoid "disconnection ".

 

3. dynamic binding

The above example of "disconnection" actually involves the dynamic binding mechanism (dynamic binding) of C ++, whileDynamic bindingOne of the key points isReference TransferIn the following example:

class Quote {public:    std::string isbn() const;    virtual double net_price(std::size_t n) const;};// Bulk_quote inherits from Quoteclass Bulk_quote : public Quote { public:    double net_price(std::size_t) const override;};

In the print_total function, net_price must be called in the form of pass-by-const-reference.

// calculate and print the pricedouble print_total(ostream &os, const Quote &item, size_t n){    double ret = item.net_price(n);    return ret;}

In the actual program, calling Quote: net_price or Bulk_quote: net_price depends on the passed parameters.

// basic is type Quote; bulk is type Bulk_quoteprint_total(cout, basic, 20); // calls Quote::net_priceprint_total(cout, bulk, 20); // calls Bulk_quote::net_price

The dynamic binding mechanism of C ++ enables the program to choose which virtual function to call based on the object type bound by reference or pointer until the program is running.

 

Summary:

Directly apply the suggestions in <C ++ Programming Language> and the explanation of dynamic binding in <C ++ Primer>

1) usePass-by-valueForSmall objects

2) usePass-by-const-referenceTo passLarge valuesThat youDon't need to modify

3)Dynamic bindingHappens whenVirtual functionIs called throughReference(Or a pointer) to a base class

 

References:

<C ++ Programming extends age_4th> ch 12.2.1

<Valid tive C ++ _ 3rd> item 20

<C ++ Primer_5th> ch 6.2, ch 15.1

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.