People sometimes ask me why it is a bad idea to cast away const in a
C++ program. It seems like a harmless thing to do, especially if
you know what are you doing. The other day I came up with the
following program that demonstrates why casting away const can be a bad
idea.
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
string a("foo"), b("bar");
cout << "a = "
<< a << endl;
cout << "b = "
<< b << endl;
a = b;
cout << " after a =
b;" << endl;
cout << "a = "
<< a << endl;
cout << "b = "
<< b << endl;
cout << " after
illegally modifying one character" << endl;
char *evilPointer =
const_cast<char*>(b.c_str());
*evilPointer = 'x';
cout << "a = "
<< a << endl;
cout << "b = "
<< b << endl;
}
How many strings start with 'x' on the final two lines? It
depends.
With gcc 3.3 I get the following:
a = foo
b = bar
after a = b;
a = bar
b = bar
after illegally modifying
one character
a = xar
b = xar
The string class that comes with gcc uses copy on write. Both a
and b are pointing at the same string representation, so the change to
b shows up as a change to a.