The correct method for the overload + operator in C ++

Source: Internet
Author: User

User-Defined types, such as string, date, plural number, Consortium, and files, often reload binary + operators to achieve object join, attaching, or merging mechanisms. However, correct implementation + operators will pose some challenges to the design, implementation, and performance. This article will give an overview of how to select the correct policy to reload this operator for user-defined types.

Consider the following expression: int x = 4 + 2;

The built-in + operator has two operands of the same type, which are added, return the right value 6, and then assigned to X. We can conclude that the built-in + is a binary, symmetric, and interchangeable operator. The result type is the same as that of the operand. According to this rule, when you define a type overload operator for a user, you should also follow the features of the corresponding built-in operators.

Defining type overloading + operators for users is a common programming task. Although C ++ provides several implementation methods, they are easy to cause design misunderstandings, which often affectCodeThe correctness, performance, and compatibility with standard library components.

Next we will analyze the features of the built-in operators and try to imitate their corresponding overload mechanism.

Step 1: select between a member function and a non-member function

You can use a class member function to implement binary operators such as: +,-, and =, for example:
Class string
{
Public:
Bool operator = (const string & S); // compare * This and S
};

This method is problematic. Compared with its built-in operators, the overloaded operators do not have symmetry here; one of its two parameters is const string * const (this parameter is implicit), and the other is: const string &. Therefore, some STLAlgorithmAnd containers cannot process such objects correctly.

Another optional method is to define the overload operator + as an external (extern) function, which includes two parameters of the same type:
String operator + (const string & S1, const string S2 );

In this way, the class string must declare this overload operator as a friend:
Class string
{
Public:
Friend string operator + (const string & S1, const string & S2 );
};

Step 2: Dilemma

As mentioned above, the built-in operator + returns the right value, which is of the same type as the operand. However, the efficiency of returning an object in the caller stack is very low, especially when processing large objects. Can we return a pointer or reference? The answer is no. Because the return pointer breaks the rule that the parameter type and return value type should be the same. Even worse, linking multiple expressions will become impossible:
String S1, S2, S3;
String res;
Res = S1 + S2 + S3; // The string * cannot be used as the return value.

Although there is a way to define additional + operator overload versions, we do not want to use this method because the returned pointer must point to the dynamically allocated object. In this case, if the pointer returned by the caller to release (delete) fails, memory leakage will occur. Obviously, returning string * is not a good idea.

Then return string & OK? The returned reference must be a valid string. It avoids Dynamic Object allocation and returns a reference to a local static object. Static objects solve the memory leakage problem, but the feasibility of this method is still questionable. In a multi-threaded application, two threads may concurrently call the + operator, resulting in confusion of the string object. In addition, because static objects always retain their statuses before calling, it is necessary to clear the static String object for each + operator call. From this point of view, returning results on the stack is still the safest and simplest solution.

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.