gpt4 book ai didi

c++ - 在 C++ 中分配和使用无类型内存块的正确方法是什么?

转载 作者:IT老高 更新时间:2023-10-28 21:42:21 26 4
gpt4 key购买 nike

到目前为止,我为这个问题得到的答案有两种完全相反的答案:“它是安全的”和“它是未定义的行为”。我决定重写整个问题,以获得更好的澄清答案,对我和任何可能通过谷歌到达这里的人来说。

另外,我删除了 C 标记,现在这个问题是 C++ 特定的

我正在创建一个 8 字节对齐的内存堆,将在我的虚拟机中使用。我能想到的最明显的方法是分配一个 std::uint64_t 数组。

std::unique_ptr<std::uint64_t[]> block(new std::uint64_t[100]);

让我们假设 sizeof(float) == 4sizeof(double) == 8。我想在 block 中存储一个 float 和一个 double 并打印该值。

float* pf = reinterpret_cast<float*>(&block[0]);
double* pd = reinterpret_cast<double*>(&block[1]);
*pf = 1.1;
*pd = 2.2;
std::cout << *pf << std::endl;
std::cout << *pd << std::endl;

我还想存储一个 C 字符串说“你好”。

char* pc = reinterpret_cast<char*>(&block[2]);
std::strcpy(pc, "hello\n");
std::cout << pc;

现在我想存储“Hello, world!”超过 8 个字节,但我仍然可以使用 2 个连续的单元格。

char* pc2 = reinterpret_cast<char*>(&block[3]);
std::strcpy(pc2, "Hello, world\n");
std::cout << pc2;

对于整数,我不需要 reinterpret_cast

block[5] = 1;
std::cout << block[5] << std::endl;

我将 block 分配为 std::uint64_t 的数组,其唯一目的是为了内存对齐。我也不希望任何大于 8 字节的内容存储在其中。如果保证起始地址为 8 字节对齐,则 block 的类型可以是任何类型。

有些人已经回答说我正在做的是完全安全的,但有些人说我肯定是在调用未定义的行为。

我是否编写了正确的代码来实现我的意图?如果不是,什么是合适的方式?

最佳答案

全局分配函数

要分配任意(无类型)内存块,全局分配函数(§3.7.4/2);

void* operator new(std::size_t);
void* operator new[](std::size_t);

可用于执行此操作 (§3.7.4.1/2)。

§3.7.4.1/2

The allocation function attempts to allocate the requested amount of storage. If it is successful, it shall return the address of the start of a block of storage whose length in bytes shall be at least as large as the requested size. There are no constraints on the contents of the allocated storage on return from the allocation function. The order, contiguity, and initial value of storage allocated by successive calls to an allocation function are unspecified. The pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type with a fundamental alignment requirement (3.11) and then used to access the object or array in the storage allocated (until the storage is explicitly deallocated by a call to a corresponding deallocation function).

而 3.11 对基本对齐要求有这样的说法;

§3.11/2

A fundamental alignment is represented by an alignment less than or equal to the greatest alignment supported by the implementation in all contexts, which is equal to alignof(std::max_align_t).

只是为了确保分配函数的行为必须像这样;

§3.7.4/3

Any allocation and/or deallocation functions defined in a C++ program, including the default versions in the library, shall conform to the semantics specified in 3.7.4.1 and 3.7.4.2.

引自 C++ WD n4527 .

假设 8 字节对齐小于平台的基本对齐(看起来确实如此,但这可以在目标平台上使用 static_assert(alignof(std::max_align_t) >= 8)) - 您可以使用全局 ::operator new 来分配所需的内存。分配后,可以根据您的大小和对齐要求对内存进行分段和使用。

这里的另一种选择是 std::aligned_storage它可以让你的内存按照任何要求对齐。

typename std::aligned_storage<sizeof(T), alignof(T)>::type buffer[100];

根据问题,我在这里假设 T 的大小和对齐方式均为 8。


最终内存块的外观示例(包括基本 RAII);

struct DataBlock {
const std::size_t element_count;
static constexpr std::size_t element_size = 8;
void * data = nullptr;
explicit DataBlock(size_t elements) : element_count(elements)
{
data = ::operator new(elements * element_size);
}
~DataBlock()
{
::operator delete(data);
}
DataBlock(DataBlock&) = delete; // no copy
DataBlock& operator=(DataBlock&) = delete; // no assign
// probably shouldn't move either
DataBlock(DataBlock&&) = delete;
DataBlock& operator=(DataBlock&&) = delete;

template <class T>
T* get_location(std::size_t index)
{
// https://stackoverflow.com/a/6449951/3747990
// C++ WD n4527 3.9.2/4
void* t = reinterpret_cast<void*>(reinterpret_cast<unsigned char*>(data) + index*element_size);
// 5.2.9/13
return static_cast<T*>(t);

// C++ WD n4527 5.2.10/7 would allow this to be condensed
//T* t = reinterpret_cast<T*>(reinterpret_cast<unsigned char*>(data) + index*element_size);
//return t;
}
};
// ....
DataBlock block(100);

我已经用合适的模板 constructget 函数等构建了 DataBlock 的更详细示例,live demo herehere with further error checking etc. .

关于别名的说明

看起来原始代码中确实存在一些别名问题(严格来说);您分配一种类型的内存并将其转换为另一种类型。

它可能在您的目标平台上按您期望的那样工作,但您不能依赖它。我见过的最实用的评论是:

"Undefined behaviour has the nasty result of usually doing what you think it should do, until it doesn’t” - hvd.

您拥有的代码可能会起作用。我认为最好使用适当的全局分配函数,并确保在分配和使用所需内存时没有未定义的行为。

别名仍然适用;一旦分配了内存 - 别名适用于它的使用方式。一旦您分配了任意内存块(如上使用全局分配函数)并且对象的生命周期开始(第 3.8/1 节)- 别名规则适用。

std::allocator 呢?

虽然 std::allocator用于同构数据容器,而您正在寻找的是类似于异构分配,您的标准库中的实现(给定 Allocator concept)提供了一些关于原始内存分配和所需对象的相应构造的指导。

关于c++ - 在 C++ 中分配和使用无类型内存块的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31436620/

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