Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 945
CXuesong Avatar asked Dec 15 '22 00:12

CXuesong


1 Answers

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.

like image 163
Mohit Jain Avatar answered Dec 22 '22 00:12

Mohit Jain