Reputation: 167
Let's say I have an image class which references a buffer containing a huge amount of data.
When the copy constructor is called, it would be nice not to have to copy the data unless that was absolutely necessary.
However, if I construct a new image object from an existing const object, the new image object begins in non-const state, which allows the image data in the new object to be altered, even though the image data in the old object could not.
I believe this is a fundamental problem in C++, because the shared_ptr object has the same problem: if you are handed a const shared_ptr, you only need to copy it into a non-const shared_ptr (via a constructor) to obtain a mutable object, which seems an insidious way to counteract const-correctness. Raw pointers do not have this problem, as such a copy is not allowed.
I understand that pointer members inherently do not inherit constness from their owner, but what I am after is a way to construct a class to make it appear that they do, to make it easy to ensure that the contents of a const object remain const.
This question provides a partial answer to this question, as it suggests using std::experimental::propagate_const
to ensure that a pointer in a const object becomes a const pointer:
How to make a deep-const pointer
However, I believe this does not solve the problem of how to ensure that a copy constructor with a const object apparently pointing to const data becomes an object which cannot alter the pointed-to data.
Upvotes: 1
Views: 54