调用std::call_once时出现异常
我正在尝试一个简单的例子来检查std::call_once(). 我尝试了以下代码,但没有做任何有用的工作。
class Test {
private:
std::string obj_name;
std::once_flag init_flag;
public:
Test(std::string name) : obj_name(name) {}
void Init() {
std::cout << "Initialization of " << obj_name << std::endl;
}
void Print() {
try {
std::call_once(init_flag, &Test::Init, this);
} catch (const std::exception& ex) {
std::cout << "Error: " << ex.what() << std::endl;
}
std::cout << "Inside Print() of "<< obj_name << std::endl;
}
};
int main() {
Test b1{"First object"};
b1.Print();
b1.Print();
return 0;
}
我期待看到Print()被调用两次但在调用std::call_once(). 我得到的输出是 -
Error: Unknown error -1
Inside Print() of First object
Error: Unknown error -1
Inside Print() of First object
编译我用过 -
g++ -g -std=c++11 -Wall -Werror
我的问题是为什么要std::call_once()抛出异常?还是我的Print()方法有问题?如果我Print()只用一个 return 语句来改变主体,它不会改变任何东西。
回答
这是一个 GCC/libstdc++ 错误,编译-pthread以修复。参见:https : //gcc.gnu.org/bugzilla/show_bug.cgi?id=55394
- same thing happened for clang too, so not for gcc only.
- More correctly it's a libstdc++ bug I suppose