简体   繁体   中英

Can there be a difference between explicit operator= call and = operator?

According to the C++ standard, can there be a difference between something.operator=(somethingElse) and something = somethingElse ?

The first appears in a template with T& something , and I'd like to know if it's safe to replace it with the more readable second version.

No there isn't. An explicit = operator invokes operator=() on a class that declares a suitable operator= method, exactly as if the operator= method was invoked directly.

This is true for all operators, not just = . That's the very definition of what an operator class method means: it specifies what gets executed when the corresponding operator is applied to an instance of the class.

Other than in copy-initialization contexts , the short operator expression is equivalent to the functional expression. Table 12 of the C++ standard draft describes the operator expressions:

Reproduced:

Subclause       Expression      As member function         As non-member function

[over.unary]  |     @a    |     (a).operator@ ( )      |    operator@(a)
[over.binary] |     a@b   |     (a).operator@ (b)      |    operator@(a, b)
[over.ass]    |     a=b   |     (a).operator= (b)      |
[over.sub]    |     a[b]  |     (a).operator[](b)      |
[over.ref]    |     a->   |     (a).operator->( )      |
[over.inc]    |     a@    |     (a).operator@ (0)      |    operator@(a, 0)

Where @ is a placeholder for the operator.


Of cause, there are other contextual use of the = operator; in function declarations, such as defaulted member functions, deleted functions and = 0; // pure virtual = 0; // pure virtual

There are tiny differences, because a = b does not always invoke an explicit operator on object a :

  • T a = b; . It is not an assignment but an initialization: it invokes a copy (or move) construction
  • a = b; when a is an intrinsic object (integer, pointer, floating point, ...): the = operator is a builtin one.
  • if T is trivially copyable, the assignement is allowed even when no operator = has been declared on the class, because the compiler use the default builtin assignement operator.

But if an operator = method exists and is selected by the overload resolution rules, the assignment operator will invoke it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM