7

I'm learning c++ and came across this const_cast operator. Consider the following example:

class Test
{  
  private:
    char name[100];
  public:
    Test(const char* n) { std::strncpy(name, n, 99); name[99]=0; }
    const char* getName() const { return name; }
}

Now a user can do

Test t("hi");
const_cast<char*>(t.getName())[0] = 'z'; //modifies private data...

Is this fine ? I mean modifying private data since the purpose of return const char* was to prevent changing private data. How do I prevent this ? (without using std::string)

4

2 回答 2

8

No this is not 'fine'. Though it is possible. But C++ doesn't force good behavior on programmers. It mainly allows you to declare things in a way that show their intended use. If a programmer decides to trick around that protection he should know what he is doing.

Bjarne Stroustrup: Yes. That's the new cast syntax. Casts do provide an essential service. The new syntax is an improvement over the C-style casts because it allows the compiler to check for errors that it couldn't with the old syntax. But the new syntax was made deliberately ugly, because casting is still an ugly and often unsafe operation.

于 2011-06-20T23:13:05.940 回答
5

No, it's not fine, but that's the whole point of const_cast. Generally, when a programmer overrides const a whole bunch of bad things may happen, and it is not advised to do that. I'm not sure if you can prevent someone from doing that though, because the point of const_cast is to override the protection generally provided by const.

于 2011-06-20T23:11:39.863 回答