I am trying a simple example to check the behavior of std::call_once(). I have tried the following code which doesn't do any useful work.
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;
}
I was expecting to see Print() called twice but getting an exception while calling std::call_once(). The output I got is -
Error: Unknown error -1
Inside Print() of First object
Error: Unknown error -1
Inside Print() of First object
To compile I've used -
g++ -g -std=c++11 -Wall -Werror
My question is why std::call_once() throwing exception? Or is it something I got wrong in my Print() method? If I change the body of Print() with just a return statement, it doesn't change anything.