gpt4 book ai didi

c++ - 通过 new[] 分配 n 个字节并用任何类型填充它?

转载 作者:IT王子 更新时间:2023-10-28 23:34:09 25 4
gpt4 key购买 nike

我想动态分配已知大小的内存(只是内存,不关心类型)并用完全相同数量的数据填充它,但任何类型(我只确定它将是原始类型)。 Ofc 稍后我会释放它。

没事吧? :

auto dest = new int8_t[n];
std::memcpy(dest, src, n);
delete[] dest;

src 是指向大小为 n(字节)的数组。我选择了 int8_t 因为这是分配一定数量内存的最清晰的方法。事实上,上面的代码并不完全是什么。 delete[] 将在 实际上 它指向的类型的指针上调用。例如,如果 src 是一个 float 组(忘记上面代码的最后一行):

float * ptr = dest;
delete[] ptr;

再说一遍。会好吗?

最佳答案

没关系,但前提是您使用 char 数组或 unsigned char 数组,因为这些类型有特殊的对齐保证:

5.3.4 New
11 When a new-expression calls an allocation function and that allocation has not been extended, the 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 ]

我强调。

另一个要求是您只能使用原始类型或 POD,因为您不调用构造函数,而是调用(微不足道的)析构函数(通过 delete)。

关于c++ - 通过 new[] 分配 n 个字节并用任何类型填充它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39668561/

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