gpt4 book ai didi

c++ - 使用placement new操作符时我真的需要担心对齐吗?

转载 作者:IT老高 更新时间:2023-10-28 23:27:48 29 4
gpt4 key购买 nike

我读到了 When should I worry about alignment?但我仍然不知道我是否必须担心放置 new 运算符返回的未对齐指针 - 就像在这个例子中一样:

class A {
public:
long double a;
long long b;
A() : a(1.3), b(1234) {}
};

char buffer[64];

int main() {
// (buffer + 1) used intentionally to have wrong alignment
A* a = new (buffer + 1) A();
a->~A();
}

__alignof(A) == 4(buffer + 1) 未与 4 对齐。但一切正常——这里有完整的例子:http://ideone.com/jBrk8

如果这取决于架构,那么我使用的是:linux/powerpc/g++ 4.x.x。

[更新] 在发布这个问题后,我阅读了这篇文章:http://virtrev.blogspot.de/2010/09/memory-alignment-theory-and-c-examples.html .也许在我的情况下唯一的缺点是性能损失,我的意思是未对齐的访问成本高于对齐?

最佳答案

当你在缓冲区上调用placement new时:

A *a = new (buf) A;

您正在调用内置的 void* operator new (std::size_t size, void* ptr) noexcept定义在:

18.6.1.3 Placement forms [new.delete.placement]

These functions are reserved, a C++ program may not define functions that displace the versions in the Standard C++ library (17.6.4). The provisions of (3.7.4) do not apply to these reserved placement forms of operator new and operator delete.

void* operator new(std::size_t size, void* ptr) noexcept;
Returns: ptr.
Remarks: Intentionally performs no other action.

(3.7.4) 的规定 包括返回的指针应该适当对齐,所以它适用于 void* operator new (std::size_t size, void* ptr) noexcept如果传入一个指针,则返回一个未对齐的指针。不过,这不会让 摆脱困境:

5.3.4 New [expr.new]

[14] Note: when the allocation function returns a value other than null, it must be a pointer to a block of storage in which space for the object has been reserved. The block of storage is assumed to be appropriately aligned and of the requested size.

因此,如果您将未对齐的存储传递给放置新表达式,则您违反了存储已对齐的假设,结果是 UB。


确实,在您上面的程序中,如果您替换 long long b__m128 b (在 #include <xmmintrin.h> 之后)然后程序会出现段错误,正如预期的那样。

关于c++ - 使用placement new操作符时我真的需要担心对齐吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11781724/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com