簡體   English   中英

std::optional 默認構造函數不是 gcc 中的 constexpr?

[英]std::optional default constructor not being constexpr in gcc?

我有以下代碼來測試我的 constexpr 可構造惰性類:

https:\/\/godbolt.org\/z\/rMLCiL<\/a>

#include <optional>

template <class T>
class Lazy
{

    using initializer_t = T (*)();
    std::optional<T> m_val = std::nullopt;
    initializer_t m_initializer;

public:
    constexpr Lazy(initializer_t initializer = initializer_t{[] { return T{}; }}) noexcept
        : m_initializer{initializer} {}

    T& operator*()
    {
        if (!m_val.has_value()) {
            m_val = m_initializer();
        }
        return *m_val;
    }
    constexpr T* operator->() { return &(**this); }
};


#include <iostream>
struct A {
    int f() { return 10; }
    ~A()
    {
        std::cout << "Goodbye A " << (void*)this << std::endl;
    }
};
extern Lazy<A> a;

int val = a->f();

Lazy<A> a{[] { return A{}; }};

int main()
{
    std::cout << val << std::endl;
}

這是 gcc 中的錯誤,還是我遺漏了什么?

<\/blockquote>

是的,可以驗證這個錯誤(程序執行期間的分段錯誤)在 GCC 9.4 之前仍然可以重現,並且程序從 GCC 10.1 開始運行良好(這意味着錯誤已修復)。 演示: https<\/a> : \/\/gcc.godbolt.org\/z\/osWa1no9Y<\/a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM