我有以下代码:
class ClassA
{
public:
ClassA(std::string str);
std::string GetSomething();
};
int main()
{
std::string s = "";
try
{
ClassA a = ClassA(s);
}
catch(...)
{
//Do something
exit(1);
}
std::string result = a.GetSomething();
//Some large amount of code using 'a' out there.
}
Run Code Online (Sandbox Code Playgroud)
我想最后一行可以访问a变量.我怎么能实现这一点,因为ClassA没有默认构造函数ClassA(),我不想使用指针?是添加默认构造函数的唯一方法ClassA吗?
sky*_*ing 11
你不能或不应该.相反,你可以在try块中使用它,例如:
try
{
ClassA a = ClassA(s);
std::string result = a.GetSomething();
}
catch(...)
{
//Do something
exit(1);
}
Run Code Online (Sandbox Code Playgroud)
原因是因为a在try引用该对象之后的块之后超出范围是未定义的行为(如果你有指向它的位置).
如果你关心a.GetSomething或任务,throw你可以放一个try-catch:
try
{
ClassA a = ClassA(s);
try {
std::string result = a.GetSomething();
}
catch(...) {
// handle exceptions not from the constructor
}
}
catch(...)
{
//Do something only for exception from the constructor
exit(1);
}
Run Code Online (Sandbox Code Playgroud)
你可以使用某种optional或只是使用std::unique_ptr.
int main()
{
std::string s = "";
std::unique_ptr<ClassA> pa;
try
{
pa.reset(new ClassA(s));
}
catch
{
//Do something
exit(1);
}
ClassA& a = *pa; // safe because of the exit(1) in catch() block
std::string result = a.GetSomething();
//Some large amount of code using 'a' out there.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1871 次 |
| 最近记录: |