我在我的程序中使用了
现在,当我尝试打印
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=]
std::atomic<>
类有一个load()
成员函数,用于读取值(原子地 :-),你可以使用它。 - Bo Perssonstd::atomic
用于为并发问题对变量进行内存访问排序。 - AJG85error: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘std::atomic<unsigned int>’ [-Werror=format=]
。我认为这个错误适用于这个问题。至少现在是我的错误。 - Gabriel Staplesprintf("%u", atomic_var)
。https://godbolt.org/z/ceWvhKbvn显示它实际上将`std::atomic<>对象复制到堆栈中,而不仅仅是底层的
T。(与大多数实现不同,当MSVC的
std::atomic无法无锁时,它在对象本身中包含一个互斥锁。因此,
sizeof(atomic<big>) == 36,而底层结构体为32,我们看到它使用了2个
movups加上额外的4字节
mov`)。因此,在只使用较旧的MSVC进行测试的代码库中可能存在此类错误。似乎在MSVC19.10(VS2017及更高版本)中已修复。 - undefined