I think s2 is a copy of s1 and even if strtok() modifies array, s2 should be modified and not s1. |
Like I said, the behavior of the program is undefined. It's not possible to reason about a the behavior of a program with undefined behavior, at least not without understanding the internal workings of the compiler.
For example, suppose I'm an optimizing compiler and I'm compiling func(). Here's a possible line of reasoning I'm allowed to follow by the language:
1. I see that func() takes a non-trivial object by value.
2. Can the copy be omitted?
3. What members of std::string are used?
4. Answer to 3: ["std::string::c_str() const"]
5. All members of std::string used in func() are const function members.
6. Answer to 2: Since the formal argument is never modified, the copy is redundant.
7. Replace the pass-by-value with a pass-by-reference-to-const.
The
const_cast<char*>(s2.c_str())
bit is just wrong. If you want to pass a pointer to an std::string's internal array, to a function that may modify its parameter, you should use
&s2[0]
instead. But note that s2.size() should be at least 1.