I'am using gcc 4.5 and want to transfer an exception to a different thread: 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;
}
The output I get:
caught
outside NULL
Seems e
is not NULL inside the thread, but then outside it is?!
What's wrong here?
I figured it out myself. std::thread makes a copy of struct Callable
first...
The following works as expected:
#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;
}
精彩评论