为什么std :: atomic的默认构造函数不默认初始化底层存储值? [英] Why does default constructor of std::atomic not default initialize the underlying stored value?

查看:138
本文介绍了为什么std :: atomic的默认构造函数不默认初始化底层存储值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为今天是美国的感恩节,所以我将被指定为土耳其来问这个问题:

Since it's Thanksgiving today in the USA, I'll be the designated turkey to ask this question:

采取一些无害的措施.具有简单普通旧数据类型(例如int)的原子:

Take something as innocuous as this. An atomic with a simple plain old data type such as an int:

atomic<int> x;
cout << x;

以上将打印出垃圾(未定义)数据.考虑到我为原子构造器

The above will print out garbage (undefined) data. Which makes sense given what I read for the atomic constuctor:

(1)默认构造函数

(1) default constructor

使原子对象处于未初始化状态.未初始化的原子对象可以稍后通过调用atomic_init来初始化.

Leaves the atomic object in an uninitialized state. An uninitialized atomic object may later be initialized by calling atomic_init.

感觉像是一个奇怪的委员会决定.但是我确定他们有他们的理由.但是我想不出另一个 std :: 类,在该类中,默认构造函数会将对象置于未定义状态.

Feels like an odd committee decision. But I'm sure they had their reasons. But I can't think of another std:: class where the default constructor will leave the object in an undefined state.

我可以看到,对于没有默认构造函数且需要去 atomic_init std :: atomic 使用更复杂的类型,这将是有意义的小路.但是更普遍的情况是在诸如引用计数,顺序标识符值和基于简单轮询的锁定之类的方案中使用具有简单类型的原子.因此,感觉这些类型没有自己的存储值零初始化"(默认初始化)很奇怪.或者至少,如果无法预测,为什么要使用默认构造函数.

I can see how it would make sense for more complex types being used with std::atomic that don't have a default constructor and need to go the atomic_init path. But the more general case is to use an atomic with a simple type for scenarios such as reference counting, sequential identifier values, and simple poll based locking. As such it feels weird for these types to be not have their own stored value "zero-initialized" (default initialized). Or at the very least, why have a default constructor if isn't going to be predictable.

未初始化的 std :: atomic 实例将很有用的理由是什么.

What's the rationale for this where an uninitialized std::atomic instance would be useful.

推荐答案

",此行为的主要原因是与C兼容. atomic_int i; 不执行初始化.为了与C兼容,等效的C ++也必须不执行任何初始化.而且由于C ++中的 atomic_int 应该是 std :: atomic< int> 的别名,因此,为了实现完全的C/C ++兼容性,该类型也必须不执行任何初始化.

As mentioned in P0883, the main reason for this behavior is compatibility with C. Obviously C has no notion of value initialization; atomic_int i; performs no initialization. To be compatible with C, the C++ equivalent must also perform no initialization. And since atomic_int in C++ is supposed to be an alias for std::atomic<int>, then for full C/C++ compatibility, that type too must perform no initialization.

幸运的是, C ++ 20似乎正在消除这种行为.

这篇关于为什么std :: atomic的默认构造函数不默认初始化底层存储值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆