【问题标题】:constexpr causes a GCC warning when used with string literalconstexpr 与字符串文字一起使用时会导致 GCC 警告
【发布时间】:2022-01-03 09:58:31
【问题描述】:

以下代码编译:

#include <iostream>


int main( )
{
    const char* const str = "This is a constant string.";

    std::cout << str << '\n';
}

但是,这个给出了警告:

    constexpr char* const str = "This is a constant string.";

这里:

warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
   37 |         constexpr char* const str = "This is a constant string.";
      |                                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~

这是 GCC 中的错误吗?我将字符串转换为指向constexpr char 数组的指针。这个警告有效吗?

现在使指针本身constexpr 完全阻止它被编译:

    const char* constexpr str = "This is a constant string.";

这里:

error: expected unqualified-id before 'constexpr'
   37 |         const char* constexpr str = "This is a constant string.";
      |                     ^~~~~~~~~

为什么指针不能是 constexpr?

【问题讨论】:

  • constexpr 适用于指针本身,而不适用于它所指向的东西,它应该是 constexpr const char* str
  • @Kaldrr 啊哈我明白了。现在有没有办法让类型本身constexpr?我的意思是constexpr (constexpr char*) str?这样做有什么好处吗?
  • 简答,不。 constexpr 并不是真正的 C++ 类型系统的一部分,没有指向 constexpr 变量的特定类型的指针,只有指针本身是 constexpr。改用指向const 的指针,因为constexpr 暗示变量为const
  • @Kaldrr 感谢您的信息。我不知道。

标签: c++ gcc compiler-warnings constexpr string-literals


【解决方案1】:

这里是否使用 constexpr 不是问题。您正在尝试将字符串文字存储在 char* const 中,它不是指向不可变数据(字符串文字是)的指针,而是具有常量地址的指针。字符串文字可以存储为 const char* 或 const char* const。

const char* str = "This is a constant string."

添加 constexpr 如下所示:

constexpr const char* str = "This is a constant string."

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    相关资源
    最近更新 更多