1

Compare the following:

I have a static member in a class that is either const constexpr or just constexpr. According to this explanation on MS Docs constexpr implies constness:

All constexpr variables are const.

However, this issues a warning in gcc 8.4:

#include <iostream>
#include <string>

struct some_struct
{
    static constexpr char* TAG = "hello";
    void member() {
        printf("printing the tag %s", TAG);
    }  
};

int main()
{
    some_struct A;
    A.member();
}

While this doesn't:

#include <iostream>
#include <string>

struct some_struct
{
    static const constexpr char* TAG = "hello";
    void member() {
        printf("printing the tag %s", TAG);
    }  
};

int main()
{
    some_struct A;
    A.member();
}

Try it in CompilerExplorer.

What is the difference?

user17732522
  • 53,019
  • 2
  • 56
  • 105
glades
  • 3,778
  • 1
  • 12
  • 34

1 Answers1

4

Does constexpr really imply const?

Yes. Constexpr variables are always const.

What is the difference?

const T* is a non-const pointer to const. It is not const.

T* const is a const pointer to non-const. It is const.

const T* const is a const pointer to const. It is const.

constexpr T* is a const pointer to non-const. It is const by virtue of being constexpr.

const constexpr T* is a const pointer to const. It is const by virtue of being constexpr.

String literals are arrays of const char, and they don't implicitly convert to a pointer to non-const char (since C++11).

eerorika
  • 232,697
  • 12
  • 197
  • 326