为什么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编译代码。
请考虑以下代码段:
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被允许通过改变foo在test2,而他们可以通过改变foo在test1(具有例如const_cast除去const从const int&是因为引用的对象实际上并不是常量中test1)。
现在,gcc,clang或MSVC似乎都没有优化test2到foo(bar()); return 0;,并且我可以理解,他们不希望浪费优化来传递很少在实践中应用的优化。
但是我至少对我对这种情况的理解是正确的,还是我错过了一些法律x上的修改方法test2?