[Bug c++/85858] -Weffc++ should not require copy ctor for const pointers

msharov at users dot sourceforge.net gcc-bugzilla@gcc.gnu.org
Tue May 22 13:26:00 GMT 2018


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

--- Comment #12 from Mike Sharov <msharov at users dot sourceforge.net> ---
(In reply to Jonathan Wakely from comment #10)
> It's simply not how C++ works.

Quite right. I already agreed with you here; we are arguing about whether it
/should/ work this way :)

> An object's lifetime is distinct from it's constness, and a pointer-to-const 
> doesn't imply anything about whether the pointed-to object is immutable.

Exactly! I can restate my gripe in these terms: C++ has no way of explicitly
marking the owner of the object or its lifetime. When f() creates object const
A a and passes it as const A* to g(), both f() and g() see the same const A
object, but f() is the owner and should be allowed to delete it, while g() has
only been granted read-only access and should not. If delete required a
non-const pointer, then f() would either keep a non-const pointer to indicate
that it owns a, or have to explicitly const_cast it to delete.

> You seem to be saying that a pointer-to-const implies
> an immortal object that will never be destroyed.

Not at all. Object lifetime is a separate subject, but const correctness should
help enforce it by restricting who gets to set it. Ideally, the object will
have exactly one owner (insert rant on the evils of shared_ptr), and that owner
will determine the lifetime of the object. If const prevented delete, the
compiler could help you catch violations of the one-owner rule that may
compromise defined object lifetime and cause undefined behavior in functions
that hold pointers to that object.

A function can only assume that the pointer it was given remains valid if the
object lifetime is explicitly known, and there is no explicit C++ way of making
it known. We can only define the lifetime in documentation. For example:

> Why should that be true for pointers to the heap
> but not pointers to the stack?

Because the stack frees all owned objects when the scope is exited and the heap
does not. The stack will call destructors to cleanup the objects, the heap will
not. Consequently the stack can be said to be the owner of local objects, but
the heap owns nothing because it destroys nothing.


More information about the Gcc-bugs mailing list