我很困惑为什么这个程序崩溃了.这是整个计划
#include<fstream>
#include<string>
#include<iostream>
#include <exception>
#include <boost/thread/thread.hpp>
void func( const std::string& filename )
{
std::ofstream outFile( filename.c_str(), std::ios::binary);
if( !outFile.is_open() )
{
std::string err("Could not open file ");
err.append(filename);
err.append(" for writing");
throw std::exception(err.c_str());
}
}
int main()
{
std::string filename("xX:\\does_not_exist.txt");
try
{
boost::thread thrd(boost::bind(&func, filename ));
thrd.join();
// func( filename ); // calling this does not cause a crash
}
catch( const std::exception& ex)
{
std::cout << ex.what() << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
环境
Windows 7
Visual Studio Express 2008
提升:尝试1.44.0和1.46.1
链接(尝试动态和静态)
基本问题是,在当前标准中,不支持将异常从一个线程移动到另一个线程.当异常在新创建的线程中保持未被捕获时,它将到达堆栈的顶部并完成程序,就像异常未被捕获一样main.考虑到tryin main在主线程的堆栈中,但异常是在完全不同的堆栈中.
这在boost线程中有记录:http://www.boost.org/doc/libs/1_46_1/doc/html/thread/thread_management.html#thread.thread_management.thread
在即将推出的标准中,支持将异常从一个线程移动到另一个线程,但您必须手动捕获和移动或使用更高级别的构造std::future.