小编ads*_*s00的帖子

使用方法失败更改constexpr对象成员

我试图constexpr通过方法更改对象成员的值但我不明白为什么它不适用于这种特定情况:

#include <iostream>

struct test
{
    int m_counter = 0;

    constexpr test()
    {
        m_counter++;
        m_counter++;
        increment();
        increment();
        increment();
    }

    constexpr void increment()
    {
        m_counter++;   
    }

    constexpr int value() const
    {
        return m_counter;
    }
};

template<int value>
constexpr void check()
{
    std::cout << value << std::endl;
}

// constexpr test t; // value = 3, why ?

int main()
{
    constexpr test t; // value = 5, ok
    check<t.value()>();
}
Run Code Online (Sandbox Code Playgroud)

当我在全局范围内创建对象时,我不明白为什么值为3.msvc和clang在两种情况下都显示5但不是gcc.谁错了?

c++ gcc object constexpr c++14

6
推荐指数
1
解决办法
270
查看次数

标签 统计

c++ ×1

c++14 ×1

constexpr ×1

gcc ×1

object ×1