在没有显式对象创建的情况下强制转换和访问隐式生命周期类型是否有效?
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 是 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.
- If my thought is correct, doesn't the above code now violate strict-aliasing rule?
- 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,代码是合法的,并且对象是隐式创建的。 (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").