How to let C++ compiler raise a warning or error when a const is assigned to a const reference?

Daniel Berlin dberlin@dberlin.org
Wed Sep 20 19:53:00 GMT 2006


On 9/18/06, Miles Bader <miles@gnu.org> wrote:
> "Peng Yu" <pengyu.ut@gmail.com> writes:
> > I think the compiler should suspect there is something wrong, because
> > the buggy code assigns the reference of a temp variable to a const
> > reference. It should be that a const reference be assigned to another
> > const reference.
>
> It's not "assigning a temp to a const reference" (that's done all the
> time, and is perfectly innocent), it's "assigning a reference to a
> variable with a certain extent to a reference with a longer-lived
> extent."  Does gcc have the information easily available to detect that?
>
Assuming it happens in part of a program we can see, we could detect
that it is stored away in a variable that may live longer than the
original reference.

We could prove that in this case, the store always happens, and thus,
there will always be a dangling reference.

However, unless you made this a flow-sensitive, context-sensitive
interprocedural analysis (which would probably be darn slow given a
large amount of code), it would be very easy to turn that "must"
information into "may" information.



More information about the Gcc-help mailing list