I have a class that looks somewhat like this:
class S
{
public:
int* data;
S() : data(new int[10]) {}
};
The constructor allocates the memory of 10 integers, and the default copy constructor as expected merely copies the pointer itself rather than the content.
Even if there is an instance of S
that has const
modifier, I can modify the data that data
points to, since that data itself does not have const
modifier. I could avoid this by making data
private and only allowing write access via a non-const
method like so:
class S
{
private:
int* data;
public:
S() : data(new int[10]) {}
int& operator(size_t i)
{
return data[i];
}
const int& operator(size_t i) const
{
return data[i];
}
};
But now I can use the copy constructor to circumvent the const
ness of the instance of S
like so:
void main()
{
const S a; // Allocates memory
S b(a); // Also points to memory allocated for a
b(1) = 3; // Writes to a even though it is not supposed to be mutable
}
What would be an elegant way to solve this problem (potentially using templates)?
- The data pointed to by an instance of
const S
should not be mutable at all using only this instance. - Copy constructor should only copy pointer, but not make a deep copy of the data.
- Both a
const S
and anS
should be creatable via a copy constructor given an instance ofS
such that theconst
instance cannot modify the data, but the non-const
instance can.