【问题标题】:Annoying C++ gcc warning message烦人的 C++ gcc 警告信息
【发布时间】:2013-06-26 18:19:03
【问题描述】:

我编写了以下程序来匹配 C++ 中的正则表达式

#include <regex.h>
#include <iostream>

using namespace std;

/*
* Match string against the extended regular expression in
* pattern, treating errors as no match.
*
* return true for match, false for no match
*/


bool match(const char *string, char *pattern)
{
    int status; regex_t re;

    if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0)
        return false;
    /* report error */

    status = regexec(&re, string, (size_t) 0, NULL, 0);
    regfree(&re);
    if (status != 0) {
        return false; /* report error */
    }
    return true;
}

int main()
{
    string str = "def fadi 100";
    bool matchExp = match(str.c_str(), "^[Dd][Ee][Ff][' '\t]+[A-z]+([,])?[''\t]+[0-9]+$");
    cout << (matchExp == true ? "Match": "No match") << endl;
}

程序按预期工作正常,但是当我使用带有 -Wall -Werror 参数的 gcc 编译代码(Linux 环境)时,我收到一条非常烦人的警告消息,内容如下:

main.cpp: In function ‘int main()’:
main.cpp:33:90: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

有没有办法强制编译器相信str.c_str()char * str 相同?如果有,怎么做?

【问题讨论】:

  • 不一样,你的代码是无效的C++11。
  • 有多烦人?它告诉您您可能有未定义的行为。总比两年后随机停止工作而你不知道为什么要好。
  • 为什么不做匹配函数 2 参数 const char * ?
  • 编译器没有抱怨str.c_str();警告是因为您试图将字符串文字 "^[Dd]...[0-9]+$" 分配给 char *pattern 参数。为什么模式需要是char * 而不是char const*
  • @Praetorian 我是第一个

标签: c++


【解决方案1】:

不,没有。该转换在 C++03 中已弃用,在 C++11 中是非法的;不要这样做。

不赞成这种转换是因为字符串文字是只读的,因此const;使用指向非const char 的指针访问它们可能会导致修改const 对象,从而调用未定义的行为。警告并不烦人;它旨在使您免于使您的应用程序崩溃 - 或更糟的情况。

另外,你在阅读警告信息时是错误的;这不是关于c_str(),而是关于将字符串文字作为char * 传递。

真正修复代码的唯一方法是将match 的第二个参数更改为const char *,而不是char *,并将传递的字符串复制到该函数内部的新缓冲区(为什么不在main()?因为使用内部缓冲区,调用方的样板文件更少)。


我还想提出完全不同的解决方案,因为问题被标记为“C++”:Boost.Regex

【讨论】:

  • 如果regex.h 中的函数没有指定正确的const-ness,他对此无能为力。告诉他“所以不要使用它”没有帮助。
  • @BlueRaja-DannyPflughoeft,我相信它确实需要const char *,所以没有任何借口。即使传递一些可以安全修改的东西也不是更好。
【解决方案2】:

有没有办法强制编译器相信str.c_str()char * str 相同?

这实际上不是这里的问题 - 您已经将 str.c_str() 作为 const char* 传递。

问题是第二个参数(也是)一个字符串文字,但类型为char*。尝试将第二个参数更改为const char*

如果这仍然引发错误(由于 regex.h 函数未指定正确的 const-ness),您将不得不在 main() 或 @987654330 中执行类似的操作@:

char pattern[] = "^[Dd][Ee]...etc";
bool matchExp = match(str.c_str(), pattern);

请参阅here 了解原因。

【讨论】:

    【解决方案3】:

    问题是字符串文字应该只分配给 const char 的指针,因此您需要更改 match 以采用 char const* 模式(这在您传递字符串文字时应该是可能的)

    【讨论】:

      【解决方案4】:

      使函数的2个参数匹配const char *,警告是因为它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-27
        • 2010-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-18
        • 2010-12-13
        • 2015-12-24
        相关资源
        最近更新 更多