在没有显式对象创建的情况下强制转换和访问隐式生命周期类型是否有效?

发布于 2025-01-11 18:37:22 字数 641 浏览 2 评论 0原文

char* t = (char*)malloc(sizeof(float) * 2);
*(float*)t = 1.0f; // or *reinterpret_cast<float*>(t) = 1.0f;
*((float*)t + 1) = 2.0f; // #1

在一些 SO 问题中,有答案说上面的代码是由于严格别名违规而导致的未定义行为。

但是,我读了论文 P0593 最近。
我认为这篇论文是说如果您使用某些操作分配/获取一些存储
(例如定义char/byte数组、malloc、operator new、...)、
您可以将存储本身视为隐式生命周期类型并使用,而无需显式创建对象,因为您想要的隐式类型将隐式创建。

  1. 如果我的想法是正确的,那么上面的代码现在不违反严格别名规则吗?
  2. 上面的代码中,是否隐式创建了一个浮点数组对象?
    (如果不是,#1 是 UB,因为我在不是数组的存储上尝试了指针算术)

(如果你听不懂我在说什么,请告诉我..我英语不好..)

char* t = (char*)malloc(sizeof(float) * 2);
*(float*)t = 1.0f; // or *reinterpret_cast<float*>(t) = 1.0f;
*((float*)t + 1) = 2.0f; // #1

In some SO questions, there are answers saying that above code is undefined behaviour because of strict-aliasing violation.

But, I read the paper P0593 recently.
I think the paper is saying If you allocate/obtain some storage using certain operations
(such as defining char/byte array, malloc, operator new, ...),
you can treat and use the storage itself as implicit-lifetime types without explicit object creation because the implicit types you want would be created implicitly.

  1. If my thought is correct, doesn't the above code now violate strict-aliasing rule?
  2. In the above code, Is a float array object created implicitly?
    (If not, #1 is UB because I tried pointer arithmetic on the storage which is not array)

(If you can't understand what i'm saying, tell me plz.. I'm not good at English..)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

这个俗人 2025-01-18 18:37:22

是的,代码是合法的,并且对象是隐式创建的。 (C++20 起)

我怀疑你是否需要 std::launder 。似乎不是, malloc 隐式执行此操作 (注意“返回一个指向合适的创建对象的指针”)。

Yes, the code is legal, and the objects are created implicitly. (since C++20)

I had doubts whether you need std::launder or not. Seems not, malloc does it implicitly (note "return a pointer to a suitable created object").

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文