user2174468
user2174468

Reputation: 239

C++ reference on static variable

I just find out that this little piece of C++ code doesn't give me the same result with clang++ and with g++:

#include <iostream>
#include <string>

using namespace std;

const string& createString(char c) {
    static string s;
    s="";
    for(int i=0; i<10; ++i) {
    s+=c;
    }
    return s;
}

int main() {
    cout << createString('a') << ' ' << createString('z') << endl;
    return 0;
}

With clang++ it writes:

aaaaaaaaaa zzzzzzzzzz

like I want it to be, but with g++ it writes:

aaaaaaaaaa aaaaaaaaaa

Why is it so? Is the g++ implementation standard compliant? And what should I do if I want a function to return a temporary "big" type by reference like here to avoid useless copy?

Upvotes: 15

Views: 1561

Answers (3)

Ben Voigt
Ben Voigt

Reputation: 283624

And what should I do if I want a function to return a temporary "big" type by reference like here to avoid useless copy ?

Call it only once per expression. For example, this will work fine:

std::cout << createString('a') << ' ';
std::cout << createString('z') << std::endl;

Upvotes: 2

NPE
NPE

Reputation: 500267

Yes, both implementations are compliant. The order of evaluation of function arguments is not specified.

Therefore, createString('a') and createString('z') can be evaluated in any order. Furthermore, createString('z') can be evaluated before or after the result of createString('a') is written out.

Since the function is stateful, and returns the state by reference, both outputs are permissible, as is zzzzzzzzzz zzzzzzzzzz.

Finally, it is worth noting that having static state would be a major headache in a multithreaded environment.

Upvotes: 23

Puppy
Puppy

Reputation: 146910

And what should I do if I want a function to return a temporary "big" type by reference like here to avoid useless copy ?

It won't be. RVO and NRVO can trivially take care of this. In addition, move semantics. In short, there's nothing problematic about returning a std::string by value at all.

Upvotes: 7

Related Questions