gpt4 book ai didi

c++ - 数据会在 placement new 分配的内存中对齐吗?

转载 作者:行者123 更新时间:2023-11-28 07:24:58 25 4
gpt4 key购买 nike

struct Alignment
{
char one;
int four;
};
Alignment a = {' ',0};
char* buf = new char[8];
Alignment* p = new (buf) Alignment(a);

由于内存对齐,Alignment a的大小为8。但是p指向的Alignment实例的大小是多少呢? placement new分配的buffer内存对齐吗?

最佳答案

The size of Alignment a is 8 because of the memory alignment.

它是 8 在您的计算机上。不要假设对象有多大。使用 sizeof。如果使用 char* buf = new char[sizeof(Alignment)]; 会好得多。

Will there be memory alignment in the buffer allocated by placement new?

是的。

嗯,有两个假设,答案是肯定的。首先,这假定您没有重载 operator new(或者您的重载满足 5.3.4。)其次,它假定您已经分配了一个适当大小的数组。

该标准明确允许完全按照您所做的去做。见 5.3.4 第 10 段:

A new-expression passes the amount of space requested to the allocation function as the first argument of type std::size_t. That argument shall be no less than the size of the object being created; it may be greater than the size of the object being created only if the object is an array. For arrays of char and unsigned char, the difference between the result of the new-expression and the address returned by the allocation function shall be an integral multiple of the strictest fundamental alignment requirement (3.11) of any object type whose size is no greater than the size of the array being created. [ Note: Because allocation functions are assumed to return pointers to storage that is appropriately aligned for objects of any type with fundamental alignment, this constraint on array allocation overhead permits the common idiom of allocating character arrays into which objects of other types will later be placed. — end note ]

关于c++ - 数据会在 placement new 分配的内存中对齐吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18921089/

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