在try-catch块之外访问变量

Dar*_*xis 7 c++ c++11

我有以下代码:

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)

原因是因为atry引用该对象之后的块之后超出范围是未定义的行为(如果你有指向它的位置).

如果你关心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)

  • 有时情况并非如此。如果必须使用唯一的异常处理来检查对象初始化,则不应将其他方法包含在 try 块中。原因是无法区分异常的来源。 (3认同)

Aby*_*byx 5

你可以使用某种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)

  • 是的,在 C++17 中,有一个 `std::Optional` 。 (3认同)