如何打印 std::atomic<unsigned int> 的值?
How can I print value of std::atomic<unsigned int>?
我在程序中使用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));
相关文章:
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 错误:隐式转换更改符号:'int'到'unsigned long'
- 如何使用多次 memcpy 转换回 std::vector<unsigned char>?
- 定义 uint= "unsigned int" 没有像我在 Visual Studio 中使用 nvcc 时预期的那样应用
- static_cast<unsigned>(签名)与标准::bit_cast<unsigned>(签名)之间有区别吗?
- 对 '(const Y) (int&, std::mersenne_twister_engine<long unsigned int,
- 错误:从'void*'到'const uint8_t* {aka const unsigned char*}'的转换无效 [-允许]
- 错误:'class std::unique_ptr<std::set<long unsigned int> >'没有名为 'size' 的成员
- 为什么在C++负数static_cast如果<unsigned>数字是常数,则不同
- 正确语法,用于统一初始化名称中带有空格的类型的临时,如unsigned int
- 如何显式调用运算符<<
- "1L << count"是什么意思?如何使用超出"unsigned long long int? "范围的语句编号打印?
- C++ - 从 "int" 到 "unsigned char" 的缩小转换无效
- 让 'std::vector<unsigned char>' 从 'std::string' 中窃取内存