constexpr和之间有什么区别const?
为什么此代码会返回警告
警告:ISO C++禁止将字符串常量转换为'char*'[ - WRrite-strings]
如果
在对象声明或非静态成员函数中使用的constexpr说明符(直到C++ 14)暗示const.函数或静态成员变量(自C++ 17)声明中使用的constexpr说明符暗示内联.
#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()
{};
Run Code Online (Sandbox Code Playgroud)
如果我添加一个const后constexpr,警告消失了:
#include <cassert>
#include <string>
#include <iostream>
struct A
{
static constexpr const char* name_ = "A";
static constexpr const char* name() { return name_; }; …Run Code Online (Sandbox Code Playgroud) 比较以下内容:
我在一个类中有一个静态成员,要么是const constexpr要么只是constexpr. 根据MS Docs上的解释,constexpr 意味着常量:
所有 constexpr 变量都是 const。
然而,这会在 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();
}
Run Code Online (Sandbox Code Playgroud)
虽然这不会:
#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; …Run Code Online (Sandbox Code Playgroud) 我正在尝试了解在测试更改时我所看到的内容.该平台是带有GCC 4.8的openSUSE 42,但它可能会影响其他人.测试代码和错误如下.
$ cat test.cxx
#include <string>
#if (__cplusplus >= 201103L)
# define STATIC_CONSTEXPR static constexpr
# define CONSTEXPR constexpr
#else
# define STATIC_CONSTEXPR static const
# define CONSTEXPR
#endif
struct Name
{
STATIC_CONSTEXPR char* GetName() {return "XXX";}
};
int main(int argc, char* arv[])
{
const char* name = Name::GetName();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
和:
$ g++ -O3 -std=c++11 test.cxx -o test.exe
test.cxx: In static member function ‘static constexpr char* Name::GetName()’:
test.cxx:13:44: warning: deprecated conversion from string constant to ‘char*’ …Run Code Online (Sandbox Code Playgroud)