在一个变体类我工作的原始存储是一个字符数组:的reinterpret_cast/static_cast并未定义的行为
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));
相关问题/答案之间有什么不同之处:(见James Kanze的评论)
https://stackoverflow.com/a/7321815/3235496。
编辑
第二个问题已经在这里有一个答案:C++ When should we prefer to use a two chained static_cast over reinterpret_cast
当然这个'new(storage)X(x);'是内存泄漏 – 2015-02-07 12:51:21
@EdHeal它通过放置new来在存储中构造X.对齐存储应该是安全的做法(例如http://stackoverflow.com/questions/4583125/char-array-as-storage-for-placement-new)。你能添加一些细节吗? – manlio 2015-02-07 13:00:39