Topic: How normative is the memory model?
Author: Sean Hunt <rideau3@gmail.com>
Date: Fri, 8 May 2009 19:01:03 CST Raw View
To what extent does C++'s memory model provide guarantees about
behavior?
For instance, is the following code valid, assuming the static_assert
succeeds?
struct S { int x,y, z; };
int main()
{
S s {1,2,3};
static_assert(static_cast<void*>(&s) == static_cast<void*>
((&s.z)-2));
cout<<*(reinterepret_cast<int*>(&s)+1);
}
The definition of struct layout provides that if this compiles, y must
exist precisely at the pointer that's dereferenced in the cout line.
However, the rules for casting indicate that what is done here is
illegal. Can the memory model be considered sufficiently normative to
make this well-defined behavior?
--
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@netlab.cs.rpi.edu]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]
Author: James Kanze <james.kanze@gmail.com>
Date: Sun, 10 May 2009 00:33:51 CST Raw View
On May 9, 3:01 am, Sean Hunt <ride...@gmail.com> wrote:
> To what extent does C++'s memory model provide guarantees
> about behavior?
I'm not sure what you're asking. C++'s memory model doesn't
specify any behavior.
> For instance, is the following code valid, assuming the
> static_assert succeeds?
> struct S { int x,y, z; };
> int main()
> {
> S s {1,2,3};
> static_assert(static_cast<void*>(&s) == static_cast<void*>
> ((&s.z)-2));
> cout<<*(reinterepret_cast<int*>(&s)+1);
> }
The code has undefined behavior, so you can't say anything about
it.
> The definition of struct layout provides that if this
> compiles, y must exist precisely at the pointer that's
> dereferenced in the cout line.
The definition of struct layout allows the compiler to insert
padding more or less wherever it wants, so there's no guarantee
concerning the placement of y. And since you're static_assert
contains undefined behavior (the expression (&s.z)-2), it
effectively is inoperative.
> However, the rules for casting indicate that what is done here
> is illegal. Can the memory model be considered sufficiently
> normative to make this well-defined behavior?
The memory model has nothing to say about this code.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S mard, 78210 St.-Cyr-l' cole, France, +33 (0)1 30 23 00 34
--
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@netlab.cs.rpi.edu]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]