【问题标题】:C++ constexpr in place aligned storage constructionC++ constexpr 就地对齐存储构造
【发布时间】:2017-10-28 10:57:17
【问题描述】:

我正在尝试创建一个对齐的变体类型,它使用 std::aligned_storage 来保存数据。有没有办法以 constexpr 方式构造一个对象?我读到你不能做新的 constexpr 放置。

#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 一样强大时,我们可以在这方面做得更好

标签: c++ c++14 variant


【解决方案1】:

没有。不能出现在常量表达式中的expressions 的长列表之一是new-expression

实现变体并使其成为constexpr-friendly 的唯一方法是使用联合。虽然,即使使用联合,您仍然无法拥有可以包含 fooconstexpr 友好变体,因为它不是文字类型(顺便说一下,它有一个非平凡的析构函数std::string 有一个重要的析构函数)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 2023-03-25
    • 2019-10-19
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    相关资源
    最近更新 更多