String operator ST + STL + associativity

I tried the following code in VC ++ 2015

#include <iostream>
#include <string>

using namespace std;

int foo(int v)
{
    cout << v << endl;
    return 10;
}

string bar(int v)
{
    cout << v << endl;
    return "10";
}

int main()
{
    auto a = foo(1) + foo(2) + foo(3);
    auto b = bar(10) + bar(20) + bar(30);
    cout << "----" << endl << a << endl << b << endl;
    return 0;
}

The result on the console is as follows

1
2
3
30
20
10
----
30
101010

As we all know, the binary + operator has left-right associativity, and it can be confirmed by three calls foo. They are called from left to right according to the instructions.

My question is, why does this not look for string::operator+? Did I have any misunderstandings?

+4
source share
2 answers

You are confused between associativity and order or evaluation .

The order in which arguments are evaluated is not specified in C ++. Associativity operator +from left to right, as you mentioned.

, operator -


( )

, , "-" ++. - : f1() + f2() + f3() (f1() + f2()) + f3() - -- +, f3 , f1() f2() .

+8

, . . :

  • (30), .
  • (20), .
  • (10), .
  • 3 2.
  • 4 1.

, , .

++ , . , , . , , ++ . , , ( , , ).

+4

Source: https://habr.com/ru/post/1669044/


All Articles