As an example of bad behavior: interaction with the implementation of gcc Copy On Write.
#include <string> #include <iostream> int main() { std::string const original = "Hello, World!"; std::string copy = original; char* c = const_cast<char*>(copy.c_str()); c[0] = 'J'; std::cout << original << "\n"; }
In action on ideone .
Jello, Peace!
Problem? As the name implies, the gcc implementation of std::string uses the counted count of the common buffer under the cover. When the line is changed, the implementation will carefully check whether the buffer is currently being shared, and if so, copy it before modifying it, ensuring that the new line using this buffer will not be affected by the new record (thus name, copy when recording).
Now, with your evil program, you get access to the shared buffer through the const method (promising not to change anything), but you are changing it!
Note that with an MSVC implementation that does not use Copy On Write, the behavior will be different ( "Hello, World!" Will print correctly).
This is exactly the essence of Undefined Behavior .
Matthieu M.
source share