在我正在开发的变体类中,原始存储是一个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://dev59.com/9VrUa4cB1Zd3GeqPpP-y#7321815(参见James Kanze的评论)。
编辑
第二个问题已经在这里有了一个答案:C++ When should we prefer to use a two chained static_cast over reinterpret_cast
new(storage) X(x);
是一个内存泄漏。 - Ed Heal