代码之家  ›  专栏  ›  技术社区  ›  Arafat Hasan

如何直接从构造函数结束C++代码?

  •  4
  • Arafat Hasan  · 技术社区  · 8 年前

    class A {
    public:
        int somevar;
        void fun() {
            // something
        }
    };
    
    class B {
    public:
        B() {
            int possibility;
            // some work
            if (possibility == 1) {
                // I want to end the program here
                kill code;
            }
        }
    };
    
    int main() {
        A a;
        B b;
        return 0;
    }    
    

    std::exit 不执行任何类型的堆栈展开,堆栈上的活动对象都不会调用其各自的析构函数来执行清理。所以 标准::退出

    3 回复  |  直到 8 年前
        1
  •  8
  •   gsamaras a Data Head    6 年前

    当构造函数失败时,您应该抛出一个异常,如下所示:

    B() {
      if(somethingBadHappened)
      {
        throw myException();
      }
    }
    

    确保在中捕获异常 main() 和所有线程输入函数。

    Throwing exceptions from constructors . 阅读中的堆栈展开 How can I handle a destructor that fails

        2
  •  3
  •   user7860670    8 年前

    仅从构造函数执行是不可能的。若你们抛出一个异常,那个么应用程序需要在入口点设置一个适当的异常处理代码,因为若你们只是抛出了一个不会被处理的异常,那个么编译器就可以跳过堆栈展开和清理。

        3
  •  -1
  •   ytoledano    8 年前

    如果不想使用异常,可以在类中使用init方法 B

    class B {
    public:
        B(/*parameters that will be used by init*/) : ...
        int init(); // actually initialize instance and return non 0 upon failure
    }