相关疑难解决方法(0)

为什么Try-Catch块会影响封闭范围内的变量?

为什么temp在捕获到第一个异常后外部变成空的?

#include <iostream>
int main()
{
    std::string temp("exception");
    int value;
    while(std::cin>> value && value != 0)
    {
         try{
              if(value > 9) throw temp;
              else std::cout << value << "\n";
            }
         catch(std::string temp)
         {
              std::cout << temp << "\n";
         }
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输入:

1
2
11
13
Run Code Online (Sandbox Code Playgroud)

输出:

1
2
exception
// Printing Empty string
Run Code Online (Sandbox Code Playgroud)

预期产量:

1
2
exception
exception
Run Code Online (Sandbox Code Playgroud)

我使用g ++ 7.3.0编译代码。

c++ try-catch

41
推荐指数
1
解决办法
2098
查看次数

const在这里允许(理论上)优化吗?

请考虑以下代码段:

void foo(const int&);

int bar();

int test1()
{
    int x = bar();
    int y = x;
    foo(x);
    return x - y;
}

int test2()
{
    const int x = bar();
    const int y = x;
    foo(x);
    return x - y;
}
Run Code Online (Sandbox Code Playgroud)

在我的标准的理解,既不x也没有y被允许通过改变footest2,而他们可以通过改变footest1(具有例如const_cast除去constconst int&是因为引用的对象实际上并不是常量中test1)。

现在,gcc,clang或MSVC似乎都没有优化test2foo(bar()); return 0;,并且我可以理解,他们不希望浪费优化来传递很少在实践中应用的优化。

但是我至少对我对这种情况的理解是正确的,还是我错过了一些法律x上的修改方法test2

c++ const compiler-optimization language-lawyer

10
推荐指数
1
解决办法
189
查看次数