Search code examples
c++c++11standards-complianceconstexpr

Non-const used in a constexpr : what does the standard say?


What does the C++11 iso standard say about such an expression :

class MyClass
{
    public:
        constexpr int test()
        {
            return _x;
        }

    protected:
        int _x;
};

_x is a non-const used in a constexpr : will it produce an error, or will the constexpr be simply ignored (as when we pass a non-const parameter) ?


Solution

  • It's perfectly fine, though somewhat useless:

    constexpr int n = MyClass().test();
    

    Since MyClass is an aggregate, value-initializing it like that will value-initialize all members, so this is just zero. But with some polish this can be made truly useful:

    class MyClass
    {
    public:
        constexpr MyClass() : _x(5) { }
        constexpr int test() { return _x; }
    // ...
    };
    
    constexpr int n = MyClass().test();  // 5