简体   繁体   English

如何优雅地初始化std :: atomic数组?

[英]How do I elegantly initialize an array of std::atomic?

Let's say I have a class with a member array of std::atomic s, where the array is sized via a computation (ie it may change based on other constants elsewhere in the program): 假设我有一个带有std::atomic s成员数组的类,其中数组通过计算来调整大小(即它可能会根据程序中其他地方的其他常量而改变):

class Foo {
  static constexpr size_t kArraySize = ComputeArraySize();
  std::atomic<size_t> atomics_[kArraySize];
};

What is the most elegant way to ensure that the atomics are all initialized to zero? 确保原子全部初始化为零的最优雅方法是什么? Can I do better than looping over the array in Foo 's constructor and explicitly storing zero? 我可以做得比在Foo的构造函数中循环数组并显式存储零更好吗? Does the answer differ for std::array ? 对于std::array ,答案是否有所不同?

Normally I would use a brace initializer here, but the derived length (which may be long) makes it difficult. 通常我会在这里使用大括号初始值设定项,但派生的长度(可能很长)会让它变得困难。

Note that I cannot assume that the instance of Foo has static storage duration. 请注意,我不能假设Foo的实例具有静态存储持续时间。

Okay, I believe I've worked this through. 好的,我相信我已经完成了这项工作。 Both of these will initialize all of the atomics to zero: 这两个都将所有原子初始化为零:

std::atomic<size_t> plain_array[kArraySize] = {};
std::array<std::atomic<size_t>, kArraySize> std_array = {};

Here's the logic: 这是逻辑:

  • [dcl.init.aggr]/1 defines arrays to be aggregates. [dcl.init.aggr] / 1将数组定义为聚合。

  • [array.cons]/1 mandates that std::array also be an aggregate. [array.cons] / 1强制std::array也是聚合。

  • [dcl.init.aggr]/7 says that if there are fewer elements of the initializer list than there are members in the aggregate, then the remaining members shall be initialized from an empty initializer list. [dcl.init.aggr] / 7表示如果初始化列表中的元素少于聚合中的成员,则其余成员应从空初始化列表初始化。 In this case, that's all members. 在这种情况下,这是所有成员。

  • [dcl.init.list]/3 defines list-initialization from an empty list for a class with a default constructor (as with std::atomic ) to cause value-initialization. [dcl.init.list] / 3为具有默认构造函数(与std::atomic )的类的空列表定义列表初始化,以导致值初始化。

  • [dcl.init]/7 says that classes without user-provided constructors are zero-initialized. [dcl.init] / 7表示没有用户提供的构造函数的类是零初始化的。 Assuming that std::array<T> contains an array of T , and that the zero representation of std::atomic<size_t> is what we expect, then we're good. 假设std::array<T>包含一个T数组,并且std::atomic<size_t>的零表示符合我们的预期,那么我们就是好的。

Now, std::atomic does have a user-provided constructor, just not a user-provided default constructor (the latter is explicitly defaulted). 现在, std::atomic 确实有一个用户提供的构造函数,而不是用户提供的默认构造函数(后者是显式默认的)。 So it doesn't technically fit the conditions of the last point. 所以它在技术上并不符合最后一点的条件。 But it seems this is an error in the standard, and has been fixed in more recent drafts. 但似乎这是标准中的一个错误 ,并已在最近的草案中得到修复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM