首页 > 解决方案 > 自定义派生的 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函数:QPushButtonsomeButton

void RaGaCCMainView::on_testButton_clicked()
{
    this->functionCallerExceptionHandler([]{
        throw CameraControlException(QString("this is an exception test"), 1);
    }, []{});
}

其实我不知道问题出在哪里。我只是检索对现有异常的引用,调用它存在显然被调用一次的函数,但无论出于何种原因执行了两次。

我只想在调用函数时检索正确返回的存储在CameraControlExceptions中的错误消息...errorMessagewhat

有人能告诉我问题出在哪里吗?

标签: c++qtinheritanceexceptionstd

解决方案


QString::toLatin1返回一个临时的QByteArray. 这在返回之前被销毁CameraControlException::what,留下一个悬空指针。

最简单的解决方法是将 的结果存储QString::toLatin1为类成员变量,使其比对CameraControlException::what.


推荐阅读