C++ constexpr in place aligned storage construction

为君一笑 提交于 2021-02-08 02:11:34

问题


I'm trying to make an aligned variant type that uses std::aligned_storage to hold the data. Is there a way to construct an object in place in a constexpr way? I read you can't do constexpr placement new.

#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);
}

回答1:


No. One of the long list of expressions that can't appear in a constant expression is a new-expression.

The only way to implement a variant and have it be constexpr-friendly is through the use of a union. Although, even with a union, you still wouldn't be able to have a constexpr-friendly variant that can contain a foo since it's not a literal type (by way of it having a non-trivial destructor, by way of std::string having a non-trivial destructor).



来源:https://stackoverflow.com/questions/46988947/c-constexpr-in-place-aligned-storage-construction

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!