Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutable Member in a ConstExpr Object in C++11

In the C++14 Standard (ISO/IEC 14882:2014) the word "non-mutable" was added in Section 5.19, Paragraph 2 (emphasis mine):

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:

  • [...]
  • an lvalue-to-rvalue conversion (4.1) unless it is applied to
    • [...]
    • a non-volatile glvalue that refers to a non-volatile object defined with constexpr, or that refers to a non-mutable sub-object of such an object, or

Therefore, this code is not correct in C++14:

class A {
    public:
        mutable int x;
};

int main(){

    constexpr A a = {1};
    constexpr int y = a.x;

    return 0;
}

However, is it correct in C++11?

This is the Defect Report (CD3) 1405 where they proposed to add non-mutable:

Currently, literal class types can have mutable members. It is not clear whether that poses any particular problems with constexpr objects and constant expressions, and if so, what should be done about it.

So I would say it is correct C++11 code. Nevertheless, I tried Clang and GCC with -std=c++11 and both output an error saying mutable variables are not allowed in a constant expression. But that constraint is something added in C++14, it was not in C++11.

Does anyone know if that code is correct in C++11?

See also Defect Report (CD3) 1428.

like image 645
J L Avatar asked Jan 25 '17 10:01

J L


1 Answers

It's C++11 defect report, then C++11 need to be fixed. Only those issues with DR, accepted, DRWP, and WP status are NOT part of the International Standard for C++.

C++11 conformed compiler must implement that DR.

For example, this pair of examples is changed because of DR 1579:

  • gcc 6.1.0
  • gcc 4.9.3

This example was taken from: Why this C++ program gives different output in C++11 & C++14 compilers

like image 72
Danh Avatar answered Sep 18 '22 22:09

Danh