利用placement new处理构造函数异常

#include <iostream>

using namespace std;

class Foo1{
    public:
        Foo1(){
            cout<<"Foo1::Foo1()"<<endl;
            throw "构造函数出错";
            _id = 2;
        }
        ~Foo1(){
            
        }
        void test(){
            cout<<"_id:"<<_id<<endl;
        }
    private:
        int _id;
};
int main(){
    Foo1* obj;
    void* p;
    try{
        p = malloc(sizeof(Foo1));
        if (p == NULL){
            throw "内存分配错误!";
        }
        obj = static_cast<Foo1*>(p);
        new(p)Foo1();
    }catch(const char* msg){
       cout << msg << endl;
       free(p);
       cout<<"catch end"<<endl;
       return 0;
    }
    obj->test();
    return 0;
}
posted @ 2019-01-15 20:52  老耗子  阅读(85)  评论(0编辑  收藏  举报