vendredi 18 janvier 2019

Warning: ISO C++ forbids converting a string constant to ‘char*’ for a static `constexpr char*` data member

Why does this code return a warning

warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]

if

A constexpr specifier used in an object declaration or non-static member function (until C++14) implies const. A constexpr specifier used in a function or static member variable (since C++17) declaration implies inline.

(cppreference.com)

#include <cassert>    
#include <string>    
#include <iostream>    

struct A     
{    
    // warning: ISO C++ forbids converting a string constant to ‘char*’    
    static constexpr char* name_ = "A";                           
    static constexpr char* name() { return name_; };             
};                                             

int main()    
{};    

If I add a const after constexpr, the warning is gone:

#include <cassert>    
#include <string>    
#include <iostream>   



struct A     
{    
    static constexpr const char* name_ = "A";    
    static constexpr const char* name() { return name_; };    
};                                             

int main()    
{};  

With g++ --version = g++ (GCC) 8.2.1 20181127,

compilation g++ -O3 -std=c++2a -Wall main.cpp -o main.

Does the constexpr not imply const on static data members?

Aucun commentaire:

Enregistrer un commentaire