Transfer from reference to design mode (on) and design mode

Source: Internet
Author: User

Transfer from reference to design mode (on) and design mode

1 Value Transfer

Value transfer isCopy the value of a real ParameterPassed to the form parameter, often used in "small objects" (small objects), as shown in the following calculation of the fact function of the factorial

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

When this function is called, the parameter passing is the value passing:

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

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

In <C ++ Programming Lauguage>, a small example contains only a pair of Point classes of int-type data members (x and y). It can also be considered as a small object.

void Point::operator+=(Point delta); // pass-by-value

 

2 reference Transfer

The reference transfer does not involve copying. What is passed to the parameter isReference of Real VariableIt has two advantages: more efficient and anti-disconnection, and is often used to transmit "large value" (large values)

2.1 more efficient

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

class Person{
private: std::string name; std::string address;};class Student: public Person{
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.

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

2.2 anti-disconnection

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

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 ()

In printNameAndDisplay, the passed parameters are not modified. If pass-by-const-reference is used, the system will avoid "disconnection ".

 

void printNameAndDisplay(Window w){    std::cout << w.name();    w.display();}// WindowWithScrollBars object will be sliced offWindowWithScrollBars  wwsb;printNameAndDisplay(wwsb);

 

 

3. dynamic binding

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

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

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

double cal_total(const Quote &item, size_t n)  // calculate the price{    double ret = item.net_price(n);    return ret;}

Call Quote: net_price or Bulk_quote: net_price, depending on the passed parameters

// basic is type Quote; bulk is type Bulk_quotecal_total(basic, 20); //  Quote::net_pricecal_total(bulk, 20);  //  Bulk_quote::net_price

The dynamic binding of C ++ is also called "delayed binding", which enables the program to choose which virtual function to call based on the type of the referenced or pointer-bound object until running.

 

 

4. Design Mode

 

As mentioned above, the key to dynamic binding is reference transfer. It also has another key-Virtual FunctionsIn Example 2.2, the display function is a virtual function, and the net_price function in Example 3 is also a virtual function.

 

4.1 Template Method

 

There is a programming convention called NVI (non-marshural interface )-Non-Virtual Interface: Declare all public functions as non-virtual, that is, virtual functions as private or protected)

 

The implementation of this NVI Convention is achieved through a design pattern-template method

1) AbstractClass: TemplateMethod is a non-virtual member function (public). The function body calls the PrimitiveOperation1 and PrimitiveOperation2 virtual functions (protected)

2) ConcreteClass: inherits from AbstractClass and overwrites two virtual functions PrimitiveOperation1 and PrimitiveOperation2.

4.2 code implementation

In this mode, in Quote 3, you can declare cal_total as a public non-virtual member function, net_price as a protected function, Bulk_quote is inherited from Quote, and the virtual function net_price is rewritten.

However, in reality, only when cal_total contains at least two operation functions similar to net_price (for example, calling net_price and then print_price) is necessary to use the design mode.

The following is a simple example of the template method mode:

class AbstractClass {public:    void TemplateMethod();protected:    virtual void PrimitiveOperation1() = 0;    virtual void PrimitiveOperation2() = 0;};class ConcreteClass : public AbstractClass {protected:    void PrimitiveOperation1() override;    void PrimitiveOperation2() override;};void AbstractClass::TemplateMethod(){    PrimitiveOperation1();    PrimitiveOperation2();}

As shown in the preceding example, the template method is about how the base class calls the operation functions in the derived class. It is a reverse control structure and is often used for code reuse.

This reverse structure also embodies a design principle, that isHollywood principles-"Don't call us. We will call you"

 

Summary:

1) usePass-by-valueForSmall objects;UsePass-by-const-referenceTo passLarge valuesThat youDon't need to modify

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

3) Tempalte method pattern-define the skeleton ofAlgorithmIn an operation,Deferring some steps to subclasses.

 

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

<Design Patterns> template method

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.