【发布时间】: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) 上重现的步骤
- 将示例另存为
customExc.cpp - 输入
make customExc.o
编辑:错误与CustomException 有关。 Foo 类与它无关。所以我把它删了。
【问题讨论】:
-
顺便说一句,你不应该返回
msg.c_str(),因为msg在what()返回时就被销毁——这意味着当用户读取它时指针将不再有效。您可能需要考虑在构建时构建它并将其存储为类成员。 -
@Raphael:我知道。我只是想让这个例子尽可能简单。而且 - 因为
what()的返回值是const- 这在实践中应该不是问题。 -
我看不出
what()的返回值是const与返回msg.c_str()的安全性有什么关系......它保证指向不存在的内存,它是未定义的行为。不要那样做! -
@meador:+1 - 没错!