CXuesong CXuesong - 1 year ago 95
C++ Question

C++ STL string operator+ associativity

I tried out 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 console is as follows

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


As we all know, binary + operator has left-to-right associativity, and it can be confirmed by the 3 invocations to
foo
. They're called from left to right by instruction order.

My question is, why does this seem not hold for
string::operator+
? Have I got into some misunderstandings?

Answer Source

You are confused between associativity and order or evaluation.

Order of evaluation of arguments is unspecified in C++. Associativity of operator + is left to right as you mentioned.

To understand this, try similar code snippet with operator -


From Order or evaluation (emphasis mine)

Except where noted below, there is no concept of left-to-right or right-to-left evaluation in C++. This is not to be confused with left-to-right and right-to-left associativity of operators: the expression f1() + f2() + f3() is parsed as (f1() + f2()) + f3() due to left-to-right associativity of operator+, but the function call to f3 may be evaluated first, last, or between f1() or f2() at run time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download