When you pass the string by reference, there is a single string that is operated on by all of the recursive calls to gen()
- instead of each call to gen()
working on its own local copy. Each recursive call to gen()
modifies the (shared) string, removing all the '?' characters; when that call returns, there are no more '?' characters left to process so it simply terminates.
when you pass the string by value, each invocation of the gen()
function gets its own local copy of the string; Any changes it makes to that string are thrown away and forgotten when the function returns to the previous level. In this case your logic is correct.
(There was also a bug which caused it to crash on my Windows machine until I fixed it: std::string
is not null-terminated, so rather than checking for std[i] == '\0'
you should do something like i < str.length()
.)