该标准对未对齐的内存访问有何说法? [英] What does the standard say about unaligned memory access?

查看:119
本文介绍了该标准对未对齐的内存访问有何说法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了有关不对齐访问的标准,但没有发现任何内容(也许我是无意的).

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?

由于许多当前的CPU支持未对齐访问,因此明智的做法是定义未实现的内存访问.是这样吗?

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;

推荐答案

不,它是UB.您无法在未对齐的内存中开始对象的生存期.来自 [basic.life] p1

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

类型为 T 的对象的生存期始于以下时间:

The lifetime of an object of type T begins when:

    获得具有 T 类型的正确对齐方式和大小的
  • 存储,并且

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

如果对象具有非空初始化,则其初始化完成,

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

[...]

因此,在您的示例中,x引用的对象的生存期甚至还没有开始,因此除了

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.

但是您的实现被允许做的是说未对齐的内存(由所使用的基础体系结构指定)实际上是对齐的,从而使您的代码在C ++抽象机下有效.我不确定是否有任何编译器会这样做.

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.

这篇关于该标准对未对齐的内存访问有何说法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆