我有类 A,它有构造函数 A(string filepath)
class A {
public:
A(string filePath);
private:
A();
}
我需要初始化 A,稍后使用它。构造函数 A 抛出异常。
int main() {
A a;
try {
a = A("./my/file/path");
} catch (exception e) {
return 1;
}
// Use a
return 0;
}
什么是最优雅的解决方案? (我不想有像 init 函数这样的东西,因为它使空的 A 对象成为可能。)
最佳答案
最优雅的解决方案可能是将所有使用 a
的逻辑移动到一个函数中
int use_a(A &a);
int main() {
try {
A a("./my/file/path");
// if we reach here, no exception was thrown
// hence a is safe to use
return use_a(a);
} catch (exception e) {
// if we reach here a never really existed
return 1;
}
}
您更喜欢避免两阶段初始化是正确的 - 这样 use_a
就可以隐式地依赖于 a
的安全使用。
关于c++ - 初始化抛出异常的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49737086/