gpt4 book ai didi

c++ - std::thread::id 默认构造函数不应该创建一个 "NULL"id 吗?

转载 作者:IT王子 更新时间:2023-10-29 00:24:44 25 4
gpt4 key购买 nike

以下代码在我的 gcc 版本 4.8.0 中失败:

#include <thread>
#include <cassert>

int main() {
std::thread::id nobody;

assert( nobody != std::this_thread::get_id() );
};

这种行为是否正确?

最佳答案

更新:Jonathan Wakely 亲切地查看了这个问题 he says (below in comments) -pthread 必须传递给编译器和链接器。如果我这样做,代码也不会因 gcc 4.7.2 而失败。所以答案显然与引用的电子邮件无关。谢谢乔纳森!


这里有一些直接来自 gcc 开发人员的引述 Jonathan Wakely's mail ,写于 2011 年:

All the comparison operators on our std::thread::id rely on undefined behaviour because our thread::id is just a pthread_t.

[...]

2) operator== uses pthread_equal, which is undefined for invalid thread IDs, POSIX says:

   If either t1 or t2 are not valid thread IDs, the behavior is undefined.
<删除>虽然它是两年前写的,但它可能仍然适用。目前我无法检查 gcc 代码库以说明更多信息。

奇怪。下面的代码:

#include <iostream>
#include <thread>

int main() {

std::cout << "Started" << std::endl;

std::thread::id nobody;

if ( nobody != std::this_thread::get_id() ) {

std::cout << "OK" << std::endl;
}

std::cout << "Finished" << std::endl;
}

产生:

Started 
OK
Finished

检查 here .但是,您的代码在 4.7.2 中确实失败了。

关于c++ - std::thread::id 默认构造函数不应该创建一个 "NULL"id 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16064785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com