[例如,当我编写使用std::promise
的代码时,并且在GCC中不包含PThread库时,会引发异常,而不是链接器错误。例如:
void product(std::promise<int> intPromise, int a, int b)
{
intPromise.set_value(a * b);
}
int main()
{
int a = 20;
int b = 10;
std::promise<int> prodPromise;
std::future<int> prodResult = prodPromise.get_future();
product(std::move(prodPromise), a, b);
std::cout << "20*10= " << prodResult.get() << std::endl;
}
如果我在没有-pthread
的情况下编译此代码,则会引发以下异常:
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
Aborted (core dumped)
如果std::promise
在内部使用pthread
库,则如果我不将-pthread
命令行选项提供给g++
,它应该会引发链接错误。但是它的编译没有任何错误,并且在运行时出现上述问题。
原因是libstdc++
使用了所谓的weak references。
我们可以轻松地追踪为什么您的特定代码示例引发异常。 set_value()
调用std::call_once
。该函数在其实现中具有the line *