c++ - 在构造函数中捕获内存分配错误?

标签 c++

我有时需要 C++ 中的一个类来分配动态内存。由于这可能会失败,因此我需要检测何时无法分配内存。通常,我会按照下面的示例执行此操作,即。我不在构造函数中分配内存,但有一个单独的方法,可以捕获 bad_alloc 异常。

有没有办法在构造函数中分配内存并捕获异常?

try {
  my_class my_instance;
}
catch ...

不起作用,因为my_instance的范围仅限于try block 。

这是一个最小的例子:

#include <iostream>

class my_class {
private:
  char * data;

public:
  my_class () {
    data = NULL;
  }

  ~my_class () {
    delete [] data;
  }

  void init () {
    data = new char [10000000000];
  }

  void write (int x) {
    data[x] = 1;
  }
};

int main() {
  my_class my_instance;
  try {
    my_instance.init();
  }
  catch (std::bad_alloc&) {
    std::cout << "Memory overflow.\n";
    return 1;
  }

  my_instance.write(10);

  std::cout << "OK.\n";
  return 0;
}

最佳答案

不是真的。 my_instance 将是无法使用的无效实例。

http://www.gotw.ca/publications/mill13.htm

关于c++ - 在构造函数中捕获内存分配错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5070057/

相关文章:

c++ - 将 int 附加到 std::string

c++ - KDTree 的模板类声明

c++ - 铿锵错误 : non-type template argument refers to function that does not have linkage -- bug?

c++ - atexit() 函数

c++ - 如何获取控件相对于窗口客户端矩形的位置?

c++ - 无序映射 : clear() does not release heap on clear()

c++ - 如何使用 ostream_iterator 显示对象的属性。?

c++ - 使用指针将第一个 (2D) 数组的值复制到第二个的函数

C++: vector<set<string>> 函数初始化

c++ - 从 enable_if 中的依赖类的 true_type/false_type typedef 获取 bool 值