简体   繁体   中英

Can one override my const C++ member function returning a const pointer to a internal non-const array using const_cast?

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)

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM