More effective C + +----(19) Understanding the source of temporary objects

Source: Internet
Author: User

Item M19: Understanding the source of temporary objects
When programmers talk to each other, they often refer to variables that require only a short period of time as temporary variables. For example, in the following swap (Swap) example thread:

Template<class t>void Swap (t& object1, t& object2) {  T temp = object1;  Object1 = Object2;  Object2 = temp;}

Temp is often referred to as a temporary variable. However, in the case of C + +, temp is not a temporary variable at all, it is just a local object of a function. (All things are object)
in C + + the real temporary object is invisible, they do not appear in your source code. Creating an unnamed non-heap (Non-heap) object produces a temporary object. This unnamed object is typically produced under two conditions: implicit type conversion and function return objects for successful invocation of the function. It is important to understand how and why these temporary objects are built, because the overhead of constructing and releasing them has a negligible impact on the performance of the program.
First consider to create a temporary object for the function to be successfully calledThis occurs when the object type that is passed to the function does not match the parameter type. For example, a function that is used to calculate the number of occurrences of a character in a string:

Returns the number of times that CH appears in STR size_t countchar (const string& STR, char ch); Char Buffer[max_string_len];char C; Read into a character and string, use setw//to avoid cache overflow, when reading a string cin >> C >> setw (Max_string_len) >> buffer; cout << "There is" << Countchar (buffer, c)     << "occurrences of the character" << C     < < "in" << buffer << Endl;

Take a look at the Countchar call. The first passed argument is a character array, but the type of the parameter to which the corresponding function is bound is const string&. This call can be made successfully only if the type mismatch is eliminated, and your compiler will gladly eliminate it for you . method is to create a temporary object of type string. Initialize the temporary object by invoking the constructor of string as a parameter in buffer. The Countchar parameter str is bound to this temporary string object. When Countchar returns, the temporary object is automatically freed.
This type conversion is convenient (albeit dangerous-see clause M5), but from an efficiency standpoint, the construction and deallocation of temporary string objects is an unnecessary overhead. there are usually two ways to eliminate it. one is to redesign your code to not allow this type of conversion to occur. This method is researched and analyzed in article M5. Another method is to modify the software without needing a type conversion.Article M21 describes how to do it.
These type conversions occur only when an object is passed through value (by value) or a constant reference (Reference-to-const) parameter is passed. It does not occur when a Reference-to-non-const parameter object is passed. Consider this function:

void Uppercasify (string& str);               Change all characters in Str                                             //to uppercase

In the case of the character count, it is possible to successfully pass a char array into Countchar, but here you try to call the Upeercasify function with a char array, it will not succeed:
Uppercasify (Subtlebookplug); Error!

There is no temporary object created for the invocation to succeed.
Assuming a temporary object is created, the temporary object is passed to the upeercasify, which modifies the temporary object and changes its character to uppercase. However, there is no effect on the true parameters of the Subtlebookplug function call; Only the string object generated from Subtlebookplug is changed temporarily. No doubt this is not what programmers want. The programmer passes the Subtlebookplug parameter into the Uppercasify function and expects to modify the value of the Subtlebookplug. The implicit type conversion of a non-temporary object is modified by the references-to-non-const when the programmer expects to modify the temporary object. This is why the C + + language prohibits the creation of temporary objects for non-reference-to-non-const references. Such a reference-to-non-const parameter does not experience this problem.
The second environment for creating temporary objects is when a function returns an object. For example, operator+ must return an object to represent the and of its two operands (see effective C + + clause 23). For example, given a type number, this type of operator+ is declared like this:

Const number operator+ (const number& LHS,                       const number& RHS);

The return value of this function is temporary because it is not named; it is just the return value of the function. You have to pay for each invocation of operator+ to construct and release this object. (For a detailed explanation of why the return value is const, see effective C + + clause 21)
Usually you don't want to pay this kind of overhead. For this function, you can switch to operator= and avoid overhead. Article M22 tells us how to do this conversion. However, for most functions that return objects, you cannot switch to a different function, so there is no way to avoid constructing and releasing the return value. At least conceptually there is no way to avoid it. Yet another dark zone between concept and reality is called optimization, and sometimes you can write functions that return objects in some way to allow your compiler to optimize temporary objects. The most common and most effective of these optimizations is the return value optimization, which is the content of the terms M20.
Sum up temporary objects are expensive, so you should remove them as much as possible, but it is more important to train yourself to find a place where you can create temporary objects. Whenever you see a constant reference (reference-to-const) parameter, there is a possibility that a temporary object will be bound to the parameter. Whenever you see a function return object at any time, a temporary object is created (later released). By learning to look for these object constructs, you can significantly enhance the ability to see the overhead behind the compiler's surface action.

Summary: A real temporary object is created when a value is passed or a constant reference, because even modifying the value of a parameter only modifies the temporary variable without making any changes to the argument, which is why it is necessary to create a temporary variable for it.

More effective C + +----(19) Understanding the source of temporary objects

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.