[cfe-dev] (Request for comments) Implicit cast kind for initialization of references.
Enea Zaffanella
zaffanella at cs.unipr.it
Mon Oct 24 08:54:59 PDT 2011
We would like to hear opinions regarding the introduction of a new
implicit cast kind. In few words, the new cast kind will be used
whenever an lvalue expression initializes a declaration having reference
type.
The simplest example is the following:
int a[5];
int *p = &a[5]; // Well-defined behavior.
int &r = *p; // Undefined behavior.
Here the sub-expression `a[5]' is an lvalue expression evaluating
off-by-one with respect to array `a', i.e., it is an invalid lvalue.
Its computation is not causing UB: its address is then taken and stored
into `p', which is still well-defined. When later initializing reference
`r' using `*p' we still do NOT read the memory at address `&a[5]', but
we nonetheless obtain an UB due to the binding of the invalid lvalue to
a reference.
In terms of standards, the relevant bit should be C++03 8.3.2 p4:
"[...] A reference shall be initialized to refer to a valid object or
function. [...]"
Similar text is in C++0x 8.3.2 p5.
The new implicit cast kind (whose name could be CK_ReferenceInit) should
be useful by applications such as static analyzers and run-time UB checkers.
In principle, this cast will only have to be added in the following
contexts:
- explicit initialization of references, here included the cases of
reference-type structure fields getting initialized using an
InitListExpr node or a constructor initializer;
- call arguments passed by reference;
- ... anything else?
Comments?
Enea.
More information about the cfe-dev
mailing list