c++ - 自定义异常中的损坏消息
问题描述
我正在尝试实现自定义类异常。
异常本身有效,但我收到损坏的输出
#include <stdexcept>
namespace Exception{
class LibraryException : public std::runtime_error
{
public:
explicit LibraryException(const std::string& message)
: std::runtime_error(""),
prefix_("LibraryException: "),
message_(message)
{
}
const char* what() const noexcept override
{
std::string out;
out += prefix_;
out += message_;
return out.c_str();
}
private:
std::string prefix_;
std::string message_;
};
class BadSizeException : public LibraryException
{
public:
explicit BadSizeException() : LibraryException("Library: Bad Size\n")
{
}
};
}
当我尝试引发异常时的输出:
°áó°áóxception:尺寸错误
我做错了什么?
解决方案
我做错了什么?
您正在返回一个指向临时对象的指针。
const char* what() const noexcept override
{
std::string out;
out += prefix_;
out += message_;
return out.c_str();
}
从返回的指针out.c_str()
仅在有效时out
有效。
要解决此问题,您需要调用.c_str()
与异常具有相同生命周期的字符串,例如成员变量。
推荐阅读
- node.js - 在 Angular 中无法加载资源:net::ERR_EMPTY_RESPONSE
- firebase - 如何在 Cloud Firestore 中编辑文档中的密钥对?
- python - 在 Python 中使用 Openpxl,创建一个新的电子表格,其中包含具有特定子字符串的行
- fortran - 如何确定 Modern Fortran 中的时间步数
- node.js - 如何修复 aws ec2 服务器上的错误“无法打开浏览器进程”?
- r - Dplyr:从字符向量中添加多个具有变异/交叉的列
- java - 当我运行以下 servlet 时,在我的 Web 浏览器中得到一个空白页作为输出
- json - 基于 JSON Schema 的文档
- c# - 恢复 SQL Server 数据库失败 SMO C#
- java - Criteria API 如何编写 = ANY(?1) 表达式?