【发布时间】:2025-12-13 06:10:02
【问题描述】:
在一个变体类中,我正在处理原始存储是一个 char 数组:
alignas(/* the strictest alignment of all types of the variant */)
char storage[/* ... */];
赋值运算符类似于:
template<class X>
void operator=(const X &x)
{
// ...code for clearing the storage and setting the tag for type X...
new(storage) X(x);
}
而获取存储对象的代码是:
template<class X>
const X &get()
{
// ...
return *reinterpret_cast<X *>(storage);
// ...
}
它似乎有效,但它总是定义良好吗?我担心安全地取消引用指针(类型别名规则是否允许?)。
当前的实现和
有什么不同吗? return *static_cast<const X *>(static_cast<const void *>(storage));
相关问题/答案:
https://*.com/a/7321815/3235496(参见James Kanze 的 cmets)。
编辑
第二个问题在这里已经有了答案:C++ When should we prefer to use a two chained static_cast over reinterpret_cast
【问题讨论】:
-
这
new(storage) X(x);肯定是内存泄漏 -
@EdHeal 它通过placement new的方式在存储中构造X。对齐存储应该是一种安全的做法(例如*.com/questions/4583125/…)。你能补充一些细节吗?
标签: c++ c++11 variant reinterpret-cast static-cast