Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've searched through the standard about unaligned access, but didn't find anything (maybe I was inadvertent).

Is it undefined behavior? Is it implementation defined?

As a lot of current CPUs support unaligned access, it would be sensible that unaligned memory access is implementation defined. Is it the case?

By unaligned access, I mean for example:

alignas(int) char buffer[sizeof(int)+1];
int &x = *new(buffer+1) int;
x = 42;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
393 views
Welcome To Ask or Share your Answers For Others

1 Answer

No, it is UB. You cannot start the lifetime of an object at unaligned memory. From [basic.life]p1

The lifetime of an object of type T begins when:

  • storage with the proper alignment and size for type T is obtained, and

  • if the object has non-vacuous initialization, its initialization is complete,

[...]

So in your example, the lifetime of the object referenced by x doesn't even begin, so any other usage of it other than mentioned in [basic.life]p6 is UB.

But what your implementation is allowed to do is say that unaligned memory (as specified by the underlying architecture used) is actually aligned, thus making your code valid under the C++ abstract machine. I'm not sure whether any compiler does this however.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...