https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85858

--- Comment #8 from Mike Sharov <msharov at users dot sourceforge.net> ---
(In reply to Jonathan Wakely from comment #7)
> Your mental model of C++ is simply not how the language works.

My mental model here is actually of const correctness, not C++ specifically.
When I pass around a const object I expect it to stay unmodified. Consider a
function that takes a const T* argument. The signature suggests that the
passed-in object will only be read and will not be modified. If that function
deletes the pointer, "bad things" will likely happen. Suddenly the object
contains garbage and you can't figure out how it happened. All called functions
took it as const, so they shouldn't have messed with it. You assume memory
corruption and onto valgrind we go.

> The const qualifier affects modification of the object, not its destruction.

This is precisely the part I have a problem with. It seems downright loony to
state that destruction is not modification when the object is most definitely
modified by it. It's like saying that if I break into your house and take
stuff, I am a criminal, but if I burn it down, it's all perfectly fine.

> void f() { const int i = 0; }
> 
> Do you think this stack variable can't be destroyed, because it's const?

What it boils down to is this: const restricts access, and so prevents
ownership. If you can't destroy a thing, you don't really own it. The standard
appears to have taken the position that ownership beats const correctness. I
instead argue in favor of const correctness, and its guarantee of invariance.

The stack variable in the example illustrates the difference between access and
ownership. f() has read-only access to i, and therefore does not own it. Who
owns i? The stack does. The stack passes i to f() with limited access, and
then, when f() terminates, the stack destroys i. This way ownership is clearly
delineated. If f() were to say delete i (assuming i were a pointer), it should
be prevented from doing so.

>   using const_int = const int;
>   const int* p = new const_int();
> 
> Do you expect to never be able to delete this object,
> instead being forced to leak it?

Consequently, const objects created with new are owned by nobody, and simply do
not make sense. Somebody has to own the allocated object, so creating a const
object should be an invalid operation.

I suppose it doesn't really matter what my opinion is in this matter. Neither I
nor you write the standard, so I'll just leave this as a closing footnote in a
bug correctly resolved INVALID.

Reply via email to