I would expect an error inside the copy constructor, but this compiles just fine with MSVC10.
class Test
{
public:
Test()
{
p = new int(0);
}
Test(const Test& t)
{
delete t.p; // I would expect an error here
}
~Test()
{
delete p;
}
private:
int* p;
};
The issue that you are running into here is that you are not changing
pper se (thuspstays immutable as you’re not changing its value), but you’re changing whatppoints to and thus are working at one additional level of indirection. This is possible because deleteing the memory associated with a pointer doesn’t change the pointer itself.In a strict sense the const-ness of the object is preserved, even though its logical constness has been violated as you pulled the rug from underneath whatever
pwas pointing to.As JonH mentioned in the comment, if you were not able to delete the object pointed to by a pointer held in a const object, you would end up with memory leaks because you wouldn’t be able to clean up properly after the object.