我正在使用gcc 4.5并希望将异常转移到另一个线程: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2179.html
#include <stdexcept>
#include <iostream>
#include <thread>
struct Callable
{
void operator()()
{
try
{
throw std::runtime_error("Bad things happened");
}
catch (...)
{
std::cout << "caught" << std::endl;
e = std::current_exception();
if (e == NULL)
{
std::cout << "inside NULL" << std::endl;
}
}
}
std::exception_ptr e;
};
int main()
{
Callable c;
std::thread t(c);
t.join();
if (c.e == NULL)
{
std::cout << "outside NULL" << std::endl;
}
else
{
std::rethrow_exception(c.e);
}
return 0;
}
我得到的输出:
caught
outside NULL
似乎e
在线程内不是NULL,但是在它之外它是?!
这有什么不对?
答案 0 :(得分:2)
我自己想通了。 std :: thread首先复制struct Callable
...
以下按预期方式工作:
#include <stdexcept>
#include <iostream>
#include <thread>
int main()
{
std::exception_ptr e;
std::thread t([&e]()
{
try
{
throw std::runtime_error("Bad things happened");
}
catch (...)
{
std::cout << "caught" << std::endl;
e = std::current_exception();
if (e == NULL)
{
std::cout << "inside NULL" << std::endl;
}
}
});
t.join();
if (e == NULL)
{
std::cout << "outside NULL" << std::endl;
}
else
{
std::rethrow_exception(e);
}
return 0;
}