Efficient C ++ function return values

Source: Internet
Author: User

1. Sometimes returning a reference can improve the efficiency. In some cases, a reference cannot be returned.

In the class assignment operator function, the reference of the returned object can significantly improve the efficiency.

 Class String <br/>{< br/> public: <br/> String & operate = (const String & other); <br/> // sum function, if there is no friend modifier, only one right parameter is allowed <br/> friendString operate + (const String & s1, const String & s2); <br/> private: <br/> char * m_data; <br/>}</p> <p> String & String: operate = (const String & other) <br/>{< br/> if (this = & other) <br/> return * this; <br/> delete m_data; <br/> m_data = new char [strlen (other. data) + 1]; <br/> strcpy (m_data, other. data); <br/> return * this; // The returned result is a reference of * this, without the need to copy the Process <br/>}

If we use the "value transfer" method above, although the function is still correct, but because the return statement needs to copy * this to the external storage unit that saves the returned value, unnecessary overhead is added, this reduces the efficiency of the value assignment function.

The implementation of the string addition function operate + is as follows:

 String operate + (const String & s1, const String & s2) <br/>{< br/> String temp; <br/> delete temp. data; // temp. data is a string containing '/0' only <br/> temp. data = new char [strlen (s1.data) + strlen (s2.data) + 1]; <br/> strcpy (temp. data, s1.data); <br/> strcat (temp. data, s2.data); <br/> return temp; <br/>}

For Addition functions, the string object should be returned using the "value transfer" method. If "reference transfer" is used, the return value of the function is a "Reference" pointing to the local object temp ". Because temp is automatically destroyed at the end of the function, the returned "Reference" is invalid.

Imagine that the addition operator overload function should be the addition of two objects in the parameter list. A new object must be generated and returned. This is different from the + = Operator. The + = Operator accumulates the objects on the right to the objects on the left. Therefore, the implementation of the + = operator should return the reference of the objects on the left of the operator.

 

2. Returning a reference to a static local variable often causes problems.
As mentioned above, the operator + function cannot return a reference to a temporary object. What about returning a reference to a static local variable? The life of a static local variable does not end with the disappearance of the function, and it seems feasible to return its reference, but this will often cause problems to the program.

 Const rational & operator * (const rational & LHS, const rational & RHs) <br/>{< br/> static rational result; // static object to which a reference will be returned <br/> result = ...; // multiply LHS by RHS and put the product inside result <br/> return result; <br/>}

The following if constant is true, and the static local variable is globally visible. Each operator * returns its reference, which is equivalent to returning its "new value ".

Bool operator = (const rational & LHS, const rational & RHs); // an operator = for rationals <br/> rational a, B, c, d; <br/>... <br/> If (A * B) = (C * D) <br/>{< br/> do whatever's appropriate when the products are equal; <br/>}< br/> else <br/> {<br/> do whatever's appropriate when they're not; <br/>}< br/>

 

3. Return temporary objects. do not define partial objects to return
String temp (S1 + S2 );
Return temp;
Three things will happen in the above Code. First, the temp object is created and initialized at the same time. Then, the copy constructor copies temp to the external storage unit that stores the returned values. Finally, temp is destroyed at the end of the function (the Destructor is called ). However, to create a temporary object and return it: Return temp (S1 + S2); the compiler directly creates and initializes the temporary object in an external storage unit, the cost for copying and structure analysis is reduced, improving the efficiency.
Because the internal data types such as int, float, and double do not have constructor and destructor, although the "Syntax of temporary variables" does not increase much efficiency, the program is more concise and easy to read.

 

4. Be sure not to return the stack pointer and constant string
Do not use the return statement to return a pointer to the "stack memory" because the function automatically disappears when it ends.

Char * getstring (void) <br/>{< br/> char P [] = "Hello World"; <br/> return P; // The compiler will warn <br/>}</P> <p> void test4 (void) <br/>{< br/> char * STR = NULL; <br/> STR = getstring (); // STR content is spam <br/> cout <STR <Endl; <br/>}

Although the function Test5 runs without errors, the design concept of the function GetString2 is incorrect. Because "hello world" in GetString2 is a constant string located in the static storage zone, it remains unchanged during the lifetime of the program. No matter when GetString2 is called, it returns the same read-only memory block.

Char * getstring2 (void) <br/>{< br/> char * P = "Hello World"; <br/> return P; <br/>}</P> <p> void test5 (void) <br/>{< br/> char * STR = NULL; <br/> STR = getstring2 (); <br/> cout <STR <Endl; <br/>}< br/>

 

5. Return the reference of the member object inside the object with caution.
Sometimes you want to make the Class Object occupy less space. Generally, you can use a pointer to the object data as a data member of the class, such as the Rectangle class member pointer pData. The upperLeft and lowerRight functions of the class only want to obtain the data content of the class and do not want to modify the content. Therefore, the function end uses const to indicate that the data members of the class cannot be changed. However, it cannot achieve the purpose of design. Although the members are private, the reference that can be modified is returned through the public function. Modify it as follows: Rectangle r (& rd); r. upperLeft (). setX (5 );

Class point <br/>{< br/> Public: <br/> point (float P1, float P2) {x = p1; y = P2 ;} <br/> void setx (float f) {X = F ;}< br/> void sety (float f) {Y = f ;}< br/> PRIVATE: <br/> float X, Y; <br/>}; </P> <p> struct rectdata <br/>{< br/> rectdata (point P1, point P2): ulhc (P1), lrhc (P2) {}< br/> point ulhc, lrhc; <br/> }; </P> <p> class rectangle <br/> {<br/> Public: <br/> rectangle (rectdata * P) {pdata = P ;} <br/> point & upperleft () const {return pdata-> ulhc ;}< br/> point & lowerright () const {return pdata-> lrhc ;} <br/> PRIVATE: <br/> rectdata * pdata; <br/> };

Therefore, you need to change the two functions so that the compiler will report an error when trying to modify the data content of a vertex.

Const point & upperleft () const {return pdata-> ulhc ;}< br/> const point & lowerright () const {return pdata-> lrhc ;}

 

 

References:

Valid C ++

High-quality C/C ++ programming guide

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.