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; }

  

原文链接: https://www.cnblogs.com/mygmh/archive/2012/09/03/2668621.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/61662

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午10:05
下一篇 2023年2月9日 上午10:05

相关推荐