Skip to content

[expr.add]/6 unfortunate example in Note #3614

@languagelawyer

Description

@languagelawyer

[expr.add]/6 says:

For addition or subtraction, if the expressions P or Q have type “pointer to cv T”, where T and the array element type are not similar, the behavior is undefined. [Note: In particular, a pointer to a base class cannot be used for pointer arithmetic when the array contains objects of a derived class type. — end note]

The paragraph was added in the resolution of CWG1504 (the normative text has been a lil bit changed by CWG1865). Description of the issue says:

The current wording is not sufficiently clear that a pointer to a base class subobject of an array element cannot be used in pointer arithmetic.

I suspect this meant something like

struct B {};
struct D : B {};
D d[3];
B* bp = &d[0];
bp + 0; // This should have become UB with the resolution of the issue

At C++11 times (when the issue was reported), [conv.ptr]/3 was saying that bp would be «pointer to the base class subobject of the derived class object». In C++17, [conv.ptr]/3 says the same thing.
C++11 [expr.add]/4 was saying that «…a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one…». We may claim that currently the Standard says mostly the same thing.
This means that expressions bp + 0, bp + 1 were/are fine (before and after the resolution of the issue). bp + 2 was/is UB, but not because of the paragraph added by the resolution of the issue.
So, the resolution of the issue changed nothing for the code above (if something like the code above was meant by the issue description). That's why I call the example in the Note unfortunate.

It is possible to construct an example with base and derived classes which would match [expr.add]/6 Note, however, this would be quite non-trivial, involving multiple or virtual inheritance, to make it possible to obtain a pointer of type "pointer to base" pointing to the derived class object, not the base class subobject.

I would suggest to change the Note to say, for example:

In particular, a pointer to int cannot be used for pointer arithmetic when the array contains objects of unsigned int type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    cwgIssue must be reviewed by CWG.not-editorialIssue is not deemed editorial; the editorial issue is kept open for tracking.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions