c++ - 自定义派生的 std::exception 类的 'what' 函数返回神秘的废话
问题描述
我有一个自定义异常类,它派生自std::exception
:
CameraControlException.h
:
#ifndef CAMERACONTROLEXCEPTION_H
#define CAMERACONTROLEXCEPTION_H
#include <QString>
#include <exception>
#include "ProxOnyx/ProxOnyxUsb1_3M.h"
class CameraControlException : public std::exception
{
public:
explicit CameraControlException(QString statusText, int errorNumber);
virtual const char *what() const noexcept;
private:
QString errorMessage;
int errorNumber;
};
#endif // CAMERACONTROLEXCEPTION_H
CameraControlException.cpp
:
#include "CameraControlException.h"
#include <iostream>
CameraControlException::CameraControlException(QString statusText, int errorNumber) :
errorMessage(QString("Status: ").append(statusText)),
errorNumber(errorNumber)
{
this->errorMessage.append("\nSome text in new line");
}
const char *CameraControlException::what() const noexcept {
// Output the message like return them:
std::cout << "this->errorMessage.toLatin1().data(): " << std::endl;
std::cout << this->errorMessage.toLatin1().data() << std::endl;
// Works well but function is called twice?!
// Output:
// Status: this is an exception test
// some text
return this->errorMessage.toLatin1().data(); // Return the message as 'const char *'
}
我有一个在自定义异常处理函数中处理异常的QMainView
命名。RaGaCCMainView
此函数捕获任何std::exception
并调用what
以检索错误消息。现在,当实际这样做时,我只会胡说八道。这是异常处理函数:
template <typename TaskFunction, typename ExceptionFunction>
void RaGaCCMainView::functionCallerExceptionHandler(
TaskFunction &&taskFunction,
ExceptionFunction &&exceptionFunction
)
{
try {
taskFunction();
} catch (std::exception& exception) { // Here i catch any exception
std::cout << "exception.what(): " << std::endl;
std::cout << exception.what() << std::endl;
// Calling what here just gives some cryptic nonsense:
// ÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝ
// NOTE: I get the output inside the 'what' function twice!
exceptionFunction();
}
}
我通过在传递包含函数特定逻辑的 lambda 的任何其他函数中调用它来使用此异常处理程序。对于这个问题,我使用了命名的on_clicked函数:QPushButton
someButton
void RaGaCCMainView::on_testButton_clicked()
{
this->functionCallerExceptionHandler([]{
throw CameraControlException(QString("this is an exception test"), 1);
}, []{});
}
其实我不知道问题出在哪里。我只是检索对现有异常的引用,调用它存在显然被调用一次的函数,但无论出于何种原因执行了两次。
我只想在调用函数时检索正确返回的存储在CameraControlException
s中的错误消息...errorMessage
what
有人能告诉我问题出在哪里吗?
解决方案
QString::toLatin1
返回一个临时的QByteArray
. 这在返回之前被销毁CameraControlException::what
,留下一个悬空指针。
最简单的解决方法是将 的结果存储QString::toLatin1
为类成员变量,使其比对CameraControlException::what
.
推荐阅读
- django - django.db.utils.ProgrammingError:列不存在第 1 行
- r - 根据 R 数据帧中的行差异为点分配唯一 ID
- apache-spark - Spark 流式传输源
- c# - 出于某种原因,我的代码将 2 添加到变量而不是 1 我不知道为什么
- go - 需要从站点中找到动态 wss url
- python - 如何使用 Python 列表中的值查询 SQLite 数据库?
- angular - 除非完全清理/重建,否则 ASP 核心 + Angular 解决方案不会在 VS 中启动
- go - 记录任何 go 例程的堆栈跟踪
- elasticsearch - elasticsearch 可以在 x86-64 linux 架构上使用 NUMA 吗?
- swift - SwiftUI 中警报中的延迟操作