Topic: Any contraints on the types of 'ptr1 - ptr2'?


Author: jason@cygnus.com (Jason Merrill)
Date: Thu, 24 Nov 1994 07:30:33 GMT
Raw View
>>>>> scott douglass <scott@newton.apple.com> writes:

> Section  5.7 does not seem to place any contraints on the _types_ of
> operands to '-' when they are both pointers. In particular, is the
> conversion pointer-to-derived to pointer-to-base allowed?

  5.7  Additive operators                                     [expr.add]

2 For subtraction, one of the following shall hold:

  --both operands have arithmetic type;

  --both  operands  are pointers to qualified or unqualified versions of
    the same completely defined object type; or

  --the left operand is a pointer to a completely  defined  object  type
    and the right operand has integral type.

Jason




Author: scott@newton.apple.com (scott douglass)
Date: 23 Nov 1994 11:42:27 GMT
Raw View
[I only have access to the May 94 WP so this has, hopefully, already been
corrected.]

Section  5.7 does not seem to place any contraints on the _types_ of
operands to '-' when they are both pointers. In particular, is the
conversion pointer-to-derived to pointer-to-base allowed?

For example, is this legal?

struct B { int b; };
struct D : public B { int d; };

ptrdiff_t g(B* b, D* d) { d - b; }  // legal?

void f() {
  D d[2];
  cout << g(&d[0], &d[1]);
}

IMO, allowing it seems unhelpful and error-prone.  I think the standard
should have language similar to the ANSI/C standard (which section 5.7 is
already largely taken from) that requires the two pointers to be of the
same type (except in qualifiers).
       --scott