C++构造函数中抛出异常要注意

// 以下代码演示了在C++构造函数中抛出异常,但是析构函数却不能被调用的场景。
// 所以,在C++构造函数中,既需要分配内存,又需要抛出异常时要特别注意防止内存泄露的情况发生 #include "stdafx.h" #include <cassert> #include <string> #include <iostream> using namespace std; class test { public: test() : m_pBuf(NULL) { m_pBuf = new int[100]; throw std::runtime_error("test"); } ~test() { if( m_pBuf != NULL ) { printf( "delete buffer...\n" ); delete[] m_pBuf; m_pBuf = NULL; } } private: int* m_pBuf; }; int main(int argc, char *argv[]) { try { test t; } catch( std::runtime_error& e ) { cout<< e.what() << endl; } return 0; }

  

posted @ 2012-09-03 13:07  特洛伊人  阅读(2154)  评论(0编辑  收藏  举报