本文介绍了将原子类型的指针分配给非原子类型的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码的行为是否定义明确?

#include <stdatomic.h>

const int test = 42;
const int * _Atomic atomic_int_ptr;
atomic_init(&atomic_int_ptr, &test);
const int ** int_ptr_ptr = &atomic_int_ptr;
printf("int = %d\n", **int_ptr_ptr); //prints int = 42


我将原子类型的指针分配给非原子类型的指针(类型相同).这是我对这个示例的看法:


I assigned a pointer to atomic type to a pointer to non-atomic type (the types are the same). Here are my thoughts of this example:

标准明确规定了 const volatile restrict 限定词与 _Atomic 限定词的区别6.2.5(p27):

The Standard explicitly specify distinction of const, volatile and restrict qualifiers from the _Atomic qualifier 6.2.5(p27):

此外,合格类型的兼容性定义为 6.7.3(p10):

Also the compatibility of qualified types is defined as 6.7.3(p10):

结合以上引用,我得出结论,原子类型和非原子类型是兼容的类型.因此,应用简单分配 6.5.16.1(p1)(临时矿)的规则:

Combining the quotes cited above I concluded that atomic and non-atomic types are compatible types. So, applying the rule of simple assigning 6.5.16.1(p1) (emp. mine):

因此,我得出的结论是,行为已得到很好的定义(即使将原子类型分配为非原子类型也是如此).

So I concluded that the behavior is well defined (even in spite of assigning atomic type to a non-atomic type).

所有问题在于,应用上述规则,我们还可以得出以下结论: 将非原子类型简单分配给原子类型 显然不正确,因为我们有专门的通用 atomic_store 函数.

The problem with all that is that applying the rules above we can also conclude that simple assignment a non-atomic type to an atomic type is also well defined which is obviously not true since we have a dedicated generic atomic_store function for that.

推荐答案

6.2.5p27 :

我认为这应该明确表明,原子限定的类型被认为与它们所基于的类型的合格或不合格版本兼容.

I think this should make it clear that atomic-qualified types are not deemed compatible with qualified or unqualified versions of the types they're based on.

这篇关于将原子类型的指针分配给非原子类型的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:21
查看更多