简体   繁体   中英

C++ string pass by value

C++ string passing by value is puzzling me here. I'm expecting that it prints out aa ab ba bb However, it prints aa aab aba abab . Why does this happen?

std::string s, ab = "ab";
test(s, 0, ab);
void test(std::string s, int i, std::string ab){
    if(i == ab.size()){
        cout << s << ' ';
        return;
    }
    for(auto c : ab){
         s += c;
         test(s, i + 1, ab);
    }
}

If I replace

s += c;
test(s, i + 1, ab);

by

test(s + c, i + 1, ab);

it will work as expected.

s += c;

append c to the local string s in every loop run, so s is modified

test(s + c ...)

append c to the local string s and pass the resulting string, s is the same in every loop run

When you use += , you add one character to s in each iteration, so you're passing a longer and longer string to test until all the characters of ab have been appended.

Perhaps it becomes more obvious if you unroll the loop:

s += ab[0]; // s is now "a"
test(s, i+1, ab);
s += ab[1]; // s is now "ab"
test(s, i+1, ab);
...

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