gou*_*oup 0 c++ inheritance qt exception std
我有一个自定义的异常类,派生自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
Run Code Online (Sandbox Code Playgroud)
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 *'
}
Run Code Online (Sandbox Code Playgroud)
我有一个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();
}
}
Run Code Online (Sandbox Code Playgroud)
我通过在传递lambda的任何其他函数中调用它来使用此异常处理程序,该lambda保存函数特定的逻辑.对于这个问题,我使用了一个名为的on_clicked函数:QPushButtonsomeButton
void RaGaCCMainView::on_testButton_clicked()
{
this->functionCallerExceptionHandler([]{
throw CameraControlException(QString("this is an exception test"), 1);
}, []{});
}
Run Code Online (Sandbox Code Playgroud)
其实我不知道问题出在哪里.我只是检索一个现有异常的引用,调用它现有的函数,它被调用一次,但无论出于何种原因执行两次.
我只想在调用函数时检索存储在CameraControlExceptions中的错误消息errorMessage正确返回what...
有人可以在问题所在的地方让我高兴吗?
QString::toLatin1返回一个临时的QByteArray.这会在CameraControlException::what返回之前被破坏,留下一个悬空指针.
最简单的修复方法是将结果存储QString::toLatin1为类成员变量,使其超出调用范围CameraControlException::what.
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |