【问题标题】:g++: const discards qualifiersg++: const 丢弃限定符
【发布时间】:2010-03-09 21:12:57
【问题描述】:

为什么我会收到 discard qualifiers 错误:

customExc.cpp: In member function ‘virtual const char* CustomException::what() const’:
customExc.cpp: error: passing ‘const CustomException’ as ‘this’ argument of ‘char customException::code()’ discards qualifiers

关于以下代码示例

#include <iostream>


class CustomException: public std::exception {

public:

    virtual const char* what() const throw() {
        static std::string msg;
        msg  = "Error: ";
        msg += code();  // <---------- this is the line with the compile error 
        return msg.c_str();
    }

    char code() { return 'F'; }
};

在关于类似问题之前,我已经在 SOF 上进行了搜索。

我已经在每个可能的地方添加了const

请赐教-我不明白这一点...

编辑: 以下是在 Ubuntu-Carmic-32bit (g++ v4.4.1) 上重现的步骤

  1. 将示例另存为customExc.cpp
  2. 输入make customExc.o

编辑:错误与CustomException 有关。 Foo 类与它无关。所以我把它删了。

【问题讨论】:

  • 顺便说一句,你不应该返回msg.c_str(),因为msgwhat()返回时就被销毁——这意味着当用户读取它时指针将不再有效。您可能需要考虑在构建时构建它并将其存储为类成员。
  • @Raphael:我知道。我只是想让这个例子尽可能简单。而且 - 因为what() 的返回值是const - 这在实践中应该不是问题。
  • 我看不出what() 的返回值是const 与返回msg.c_str() 的安全性有什么关系......它保证指向不存在的内存,它是未定义的行为。不要那样做!
  • @meador:+1 - 没错!

标签: c++ g++ constants


【解决方案1】:

CustomException::what 呼叫CustomException::codeCustomException::what 是一个 const 方法,由 const after what() 表示。由于它是一个 const 方法,它不能做任何可能修改自身的事情。 CustomException::code 不是 const 方法,这意味着它not 承诺不会修改自己。所以CustomException::what 不能调用CustomException::code

请注意,const 方法不一定与 const 实例相关。 Foo::bar 可以将其 exc 变量声明为非常量并调用像 CustomException::what 这样的 const 方法;这只是意味着CustomException::what 承诺不会修改exc,但其他代码可能会。

C++ 常见问题解答中有更多关于 const methods 的信息。

【讨论】:

  • @Josh:现在我明白了 - 因为... what() promises not to modify exc ...,我终于接受了你的回答
【解决方案2】:
   int code() const { return 42; }

【讨论】:

  • 感谢这对我有帮助。我将 const 放在函数名之前而不是之后。
【解决方案3】:

您的 what() 是 const 成员函数,但 code() 不是。

只需将code() 更改为code() const

【讨论】:

    【解决方案4】:

    您的code() 成员函数未声明const。从 const 成员函数(本例中为 what())调用非 const 成员函数是非法的。

    使您的code() 成员成为常量。

    【讨论】:

    • @meador:方法上的 const 意味着 this 将是此方法中的指向 const 的指针。如果您意识到这一点,则错误消息非常有意义:当您尝试从 what() 调用 code() 时,您正在尝试将 (const CustomException*) this 转换为 (CustomException*)this,从而丢弃 cv 限定符 (常量)
    • 我认为@rmeador 提出了一个很好的观点。我已经习惯了那个错误信息,但它可以很容易地说“Cannot call ‘char customException::code()’ from ‘virtual const char* CustomException::what() const’ because ‘char customException::code()’ is not a const member function.
    • FWIW,Clang 给出了一个更好的错误(通常是这种情况):test.cpp:11:12: error: member function 'code' not viable: 'this' argument has type 'const CustomException', but function is not marked const msg += code(); // &lt;---------- this is the line with the compile error ^~~~ test.cpp:15:8: note: 'code' declared here char code() { return 'F'; }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多