Thomas said:
AndyRB said something like:
...[rip]...
"In Java, references are constrained to point only to the beginnings of
objects. In C++, you can do arithmetic on pointers and make pointers
point anywhere in the address space. "
I understand what you are saying here, but in c++ you can legally only
point to an object or one past the end of a object, otherwise you have
undefined behaviour.
That is correct, but by "legally" you mean simply compliant with the
standard.
No, in this specific case I mean writing erroneous code which is
explicitly stated as invoking undefined behaviour.
FWIW, non-compliant C++ is still C++.
non-compliant c++ code or non-compliant implementation?
If you are talking about code that invokes undefined behaviour (which
is the kind of code Roedy described in his statement) then what you
have is erroneous c++ code. The problem is many newbies (quite possibly
Roedy's target audience) are ignorant of undefined behaviour and think
that if their c++ code simply compiles then it must be valid c++. In
reality the standard places no requirements on such code whatsoever.
From C++'s point of view
{chuckle} it *does* allow you point "anywhere in the address space".
C++ allows you to map an integer address to a pointer (mapping is
implementation defined).
However:
int i;
int * p = &i;
++p; //Ok p points one past i
++p; //undefined behaviour.
My point is specifically concerning pointer arithmetic, which Roedy
mentioned explicitly in his statement.
I have
had a similar argument about all this before, regarding Std. C.
Std C has the precisely identical requirement about where a pointer can go
and remain trustworthy. At the beginning or one past: in fact the C
specification actually uses the term "object" as well. The only problem
with all this is that you cannot write malloc() in Std C, nor can you write
any device driver I can think of, but they are still regarded as being coded
in C.
Such very low-level code usually falls under the category of
implementation-defined behaviour and relies on guarantees given by the
implementation, but that is very different from undefined behaviour.
As such, when discussing the abilities of a language, in the C++ case Roedy
said it properly.
No, in c++ you cannot use pointer arithmetic to point to anywhere
within the address space, it is explicitly undefined behaviour
(consider a segmented memory model).