【发布时间】:2014-10-10 20:38:27
【问题描述】:
我正在使用std::aligned_storage,需要在aligned_storage 中存储数组类型。以下代码在 Visual cpp 中编译,但不是 Clang。
template <typename T>
struct Foo
{
typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type store;
template <typename... Args>
Foo(Args&&... args)
{
new (&store) T { std::forward<Args>(args)... };
}
void Release()
{
reinterpret_cast<T*>(&store)->~T(); // Clang problems here
}
};
Foo<int> a(2); // ok
Foo<int[3]> b(1, 2, 3); // error in clang
具体错误是:
expression of non-scalar type 'T' (aka 'int [3]') cannot be used in a pseudo-destructor expression
这是有效的 C++,我应该如何手动正确地销毁数组类型?
【问题讨论】:
-
将您的模板专门用于数组类型?
-
提示:
union{T v;} store;还定义了一个适合存储T的方法,而无需调用任何讨厌的 ctor。 -
@Deduplicator 这个例子被大大简化了,有充分的理由在 c++ 中更喜欢aligned_storage 而不是联合。
-
@MattBierner:请说出一个在这种情况下更喜欢
std::aligned_storage而不是union的充分理由。 (感觉就像你减少了很多测试用例,当然。)