0
我正在尝试使用std :: aligned_storage来保存数据的对齐变体类型。有没有一种方法可以用constexpr的方式构建一个对象?我读过你不能做constexpr安置新的。C++ constexpr in place aligned storage construction
#include <iostream>
#include <string>
struct foo
{
foo(std::string a, float b)
: bar1(a), bar2(b)
{}
std::string bar1;
float bar2;
};
struct aligned_foo
{
template<typename... Args>
aligned_foo(Args&&... args)
{
//How to constexpr construct foo?
data_ptr = ::new((void*)::std::addressof(storage)) foo(std::forward<Args>(args)...);
}
std::aligned_storage<sizeof(foo)> storage;
foo* data_ptr;
};
int main()
{
aligned_foo("Hello", 0.5);
}
'std :: string'没有'constexpr'构造函数,所以不太可能。 –
**简答:**否**长答案:**其中一个可能的原因:类类型的对象的生命周期在其构造函数完成时开始。对于'constexpr'上下文来说,管理这种生命周期的唯一有效方法是使用*自动存储持续时间*或*静态存储持续时间*的对象 - 因为编译器可以轻松推理这些生命周期。也许当我们的编译器像Rust一样有能力时,我们可以在这方面做得更好 – WhiZTiM