首页 > 解决方案 > 自定义异常中的损坏消息

问题描述

我正在尝试实现自定义类异常。

异常本身有效,但我收到损坏的输出

#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:尺寸错误

我做错了什么?

标签: c++stringc++11exception

解决方案


我做错了什么?

您正在返回一个指向临时对象的指针。

   const char* what() const noexcept override
   {
      std::string out;
      out += prefix_;
      out += message_;
      return out.c_str();
   }

从返回的指针out.c_str()仅在有效时out有效。

要解决此问题,您需要调用.c_str()与异常具有相同生命周期的字符串,例如成员变量。


推荐阅读