g++: const 丢弃限定符

2022-01-23 00:00:00 g++ constants c++

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

why do I get a discard qualifiers error:

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 上进行了搜索.

I have searched around on SOF before regarding simular issues.

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

I have already added a const on every possible place.

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

Please enlighten me - I don't get the point...

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

EDIT: here are the steps to reproduce on Ubuntu-Carmic-32bit (g++ v4.4.1)

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

EDIT:错误与CustomException有关.Foo 类与它无关.所以我把它删了.

EDIT: The error is related to CustomException. The class Foo has nothing to do with it. So I have deleted it.

推荐答案

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

CustomException::what calls CustomException::code. CustomException::what is a const method, as signified by the const after what(). Since it is a const method, it cannot do anything that may modify itself. CustomException::code is not a const method, which means that it does not promise to not modify itself. So CustomException::what can't call CustomException::code.

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

Note that const methods are not necessarily related to const instances. Foo::bar can declare its exc variable as non-const and call const methods like CustomException::what; this simply means that CustomException::what promises not to modify exc, but other code might.

C++ 常见问题解答有更多关于 const 的信息方法.

The C++ FAQ has a bit more information on const methods.

相关文章