mercredi 25 février 2015

C++ Preventing const methods from changing data through a member pointer or reference

Say I have a simple class like this



class Foo
{
public:
void foo()const
{
str[5] = 'x';
x = 4;
}
private:
char *str; //some referenced data, not owned by Foo
int &x; //references as well
};


This is valid because in the const method, its just the pointer itself that becomes const, not the data it points to. However in many cases that is not what I desired and I want a compile error if a const method tries to change these members contents (either directly or by calling a non-const method on that member).


Is there a standard solution to this?


I think some kind of wrapper class should be able to achieve this, and should also be something the compiler optimises out, although haven't sat down to try and design such a thing to cover all cases giving say a strong_const<char*> str and strong_const<int&> (also not sure on a good name...).


Aucun commentaire:

Enregistrer un commentaire