gpt4 book ai didi

c++ - 普通旧数据和 `std::memcpy` 对齐问题

转载 作者:太空宇宙 更新时间:2023-11-04 15:01:17 25 4
gpt4 key购买 nike

正在尝试回复 another question ,我提出了一个解决方案,它使用 std::memcpy() 将泛型类型存储在 char 的缓冲区中。

我怀疑存储 POD 可能存在的内存对齐问题(我知道使用非 POD 类型,如 std::string,是非常非常危险的)。

简而言之:以下程序存在内存对齐问题?

如果是,是否可以编写安全的类似内容(将 POD 值存储在 char 缓冲区中)?以及如何?

#include <cstring>
#include <iostream>

int main()
{
char buffer[100];

double d1 { 1.2 };

std::memmove( buffer + 1, & d1, sizeof(double) );

double d2;

std::memmove( & d2, buffer + 1, sizeof(double) );

std::cout << d2 << std::endl;

return 0;
}

最佳答案

这是安全的。

[basic.types]/2: For any trivially copyable type T, if two pointers to T point to distinct T objects obj1 and obj2, where neither obj1 nor obj2 is a base-class subobject, if the underlying bytes (1.7) making up obj1 are copied into obj2, obj2 shall subsequently hold the same value as obj1.

由于 double 是可简单复制的,因此您的代码定义明确。

关于c++ - 普通旧数据和 `std::memcpy` 对齐问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39832733/

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