使用指针成员变量引发异常时发生内存泄漏

Memory leak on throwing an exception with a pointer member variable

我有以下问题:

每次抛出以下异常时,我都会收到 Valgrind 内存泄漏警告:

我能够可靠地追溯到程序中的 throw MyException{pointer} 语句。 - 如果我将它们注释掉,警告就会消失。我有多个其他异常 类 可以完美运行。它们之间唯一的区别是指针变量的存在。

编辑:我用 std::string 作为参数尝试了相同的例外:Valgrind 错误仍然存​​在。

valgrind 错误:

144 bytes in 1 blocks are possibly lost in loss record 7 of 15

(文件信息指向我已经提到的 throw MyException{pointer} 语句。

我的例外情况:

// Forward declaration
class PointerClass;  

class MyException : public std::exception
{
public:
  MyException() = delete;

  MyException(PointerClass* pointer) : pointer_{pointer}
  {};

  MyException(const MyException& other) = default;

  MyException& operator=(MyException& other) = default;

  ~MyException() = default;  

  const char* what() const noexcept
  {
    return "my exception.";
  }

  const PointerClass* getPointer() const noexcept
  {
    return pointer_;
  }

private:
    PointerClass* pointer_ = nullptr;
  };

有谁知道为什么会这样以及如何解决?

我设法解决了问题:我的收获是:

catch(Except::CustomException& exception)
{
  std::cout << "Exception occurred" << std::endl;
  exit(0);
}

这是导致所有问题的原因。 现在我用

catch(Except::CustomException& exception)
{
  std::cout << "Exception occurred" << std::endl;
  flag = true;
}

if(flag)
{
   exit(0);
}

这不会导致泄漏。