C++在构造函数中捕获异常

use*_*735 7 c++ constructor exception-handling exception

如何在使用异常时保护自己不使用未完全创建的对象?我应该抓住构造函数吗?或者这可能是不好的做法?如果我将捕获构造函数对象将被创建.

#include <stdio.h>

class A
{
public:
    A()
    {
        try {
            throw "Something bad happened...";
        }
        catch(const char* e) {
            printf("Handled exception: %s\n", s);
        }
        // code continues here so our bad/broken object is created then?
    }
    ~A() 
    { 
        printf("A:~A()"); 
    }

    void Method()
    { // do something
    }
};

void main()
{
    A object; // constructor will throw... and catch, code continues after catch so basically we've got 
              // broken object.

    //And the question here: 
    //
    //* is it possible to check if this object exists without catching it from main? 
    // &object still gives me an address of this broken object so it's created but how can I protect myself 
    // from using this broken object without writing try/catch and using error codes?
    object.Method(); // something really bad. (aborting the program)

};
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 9

语言本身没有以任何可检测的方式对象"无效"的概念.

如果异常表明无法创建有效对象,则不应在构造函数中处理; 重新抛出它,或者首先不抓住它.然后程序将离开正在创建的对象的范围,并且将无法错误地访问它.

如果由于某种原因这不是一个选项,那么你需要以自己的方式将对象标记为"无效"; 也许在构造函数的末尾设置一个布尔成员变量来表示成功.这是不稳定且容易出错的,所以除非你有充分的理由,否则不要这样做.