【问题标题】:Corrupted message in custom exception自定义异常中的损坏消息
【发布时间】:2018-05-02 16:24:20
【问题描述】:

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

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

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

我做错了什么?

【问题讨论】:

  • 一旦what函数返回(使用指针)局部变量out(以及返回的指针指向的数据)会发生什么?

标签: c++ string c++11 exception


【解决方案1】:

我做错了什么?

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

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

out.c_str()返回的指针只有在out有效时才有效。

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

【讨论】:

    【解决方案2】:

    正如 Drew 所说,您在其范围之外使用了本地对象指针。可能的解决方案。

    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
       {
          buffer_ = prefix_ + message_;
          return buffer_.c_str();
       }
    
    private:
       std::string prefix_;
       std::string message_;
       mutable std::string buffer_;  // Now buffer will live between what() calls.
    };
    

    mutable 是因为what() 的常量。这样您就可以更改buffer_ 的值。

    【讨论】:

      猜你喜欢
      • 2015-11-04
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 2014-09-28
      • 1970-01-01
      • 1970-01-01
      • 2014-02-04
      • 1970-01-01
      相关资源
      最近更新 更多