如何打印 std::atomic<unsigned int> 的值?

How can I print value of std::atomic<unsigned int>?

本文关键字:lt unsigned int 的值 gt atomic 何打印 打印 std      更新时间:2023-10-16

我在程序中使用std::atomic<unsigned int>。如何使用printf打印其值?如果我只使用%u,它就不起作用。我知道我可以使用std::cout,但我的程序中充斥着printf调用,我不想替换它们中的每一个。以前我使用unsigned int而不是std::atomic<unsigned int>,所以我只是在printf调用的格式字符串中使用%u,因此打印效果很好。

当我现在尝试打印std::atomic<unsigned int>来代替常规unsigned int时,得到的错误是:

error: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘std::atomic<unsigned int>’ [-Werror=format=]

另一个选项,您可以使用原子变量的load()方法。例如:

std::atomic<unsigned int> a = { 42 };
printf("%un", a.load());
template<typename BaseType>
struct atomic
{
    operator BaseType () const volatile;
}

使用类型转换来提取基础值。

printf("%u", unsigned(atomic_uint));
相关文章: