I just discovered the most baffling error and I don't understand why the compiler did not flag it for me. If I write the following:
string s = "abcdefghijkl";
cout << s << endl;
s.substr(2,3) = "foo";
s.substr(8,1) = '.';
s.substr(9,1) = 4;
cout << s << endl;
The compiler has no problem whatsoever with this, and the assignment statements appear to have no effect, based on what's printed out. In contrast,
s.front() = 'x';
has the effect I'd expect (since front
returns a reference to a character) of changing the underlying string, and
s.length() = 4;
also has the expected effect of generating a compiler error complaining that you can't assign to something that isn't an lvalue, because length
returns an integer. (Well, a size_t
anyway.)
So... why on earth does the compiler not complain about assigning to the result of a substr
call? It returns a string value, not a reference, so it shouldn't be assignable, right? But I've tried this in g++
(6.2.1) and clang++
(3.9.0), so it doesn't seem to be a bug, and it also doesn't seem to be sensitive to C++ version (tried 03, 11, 14).