在汇总初始化原子成员
似乎无法使用C ++ 14初始化原子成员。以下无效(在gcc 8.0.1.1 上播放
#include <atomic>
#include <iostream>
struct stru {
std::atomic_int32_t val_0;
std::atomic_int32_t val_1;
};
int main() {
auto p = new stru{0, 1};
std::cout << p->val_0 << ", " << p->val_1 << std::endl;
}
:
error: use of deleted function 'std::atomic<int>::atomic(const std::atomic<int>&)'
auto p = new stru{0, 1};
^
) 原子类型既不可复制,也不是可移动的,因此不可复制。但是,以下似乎有效( live on GCC 8.0.1 )。
#include <atomic>
#include <iostream>
struct stru {
std::atomic_int32_t val_0;
std::atomic_int32_t val_1;
};
int main() {
auto p = new stru{};
std::cout << p->val_0 << ", " << p->val_1 << std::endl;
}
这有效地执行了零初始化,因此无法初始化到零以外的值。有什么方法可以初始化到其他指定的值?
There seems no way to initialize atomic members in aggregate using C++14. The following doesn't work (live on gcc 8.0.1):
#include <atomic>
#include <iostream>
struct stru {
std::atomic_int32_t val_0;
std::atomic_int32_t val_1;
};
int main() {
auto p = new stru{0, 1};
std::cout << p->val_0 << ", " << p->val_1 << std::endl;
}
The error message:
error: use of deleted function 'std::atomic<int>::atomic(const std::atomic<int>&)'
auto p = new stru{0, 1};
^
This is because atomic types are neither copyable nor movable, and is thus not copy-initializable. The following seems to work however (live on gcc 8.0.1).
#include <atomic>
#include <iostream>
struct stru {
std::atomic_int32_t val_0;
std::atomic_int32_t val_1;
};
int main() {
auto p = new stru{};
std::cout << p->val_0 << ", " << p->val_1 << std::endl;
}
This effectively performs zero initialization, and is thus unable to initialize to values other than zero. Is there any way to initialize to other specified values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
帕特里克的解决方案有效,但他的解释对我来说并不正确。因此,我发布了我在这里找到的解释。对于代码
auto p = new stru {{0},{1}};
汇总初始化效果启动:因此,从Brad-Init列表中复制列表intialized,而不是复制初始化。
Patrick's solution works, but his explanation doesn't look right to me. So I post the explanation I find here. For the code
auto p = new stru{{0}, {1}};
aggregate initialization kicks in with the effect:As a result, instead of copy initialization, the members are copy list-initialized from the braced-init-list.
1
和0
不是std :: atomic_int32_t
s。以下工作:编辑:为什么会发生这种情况? 复制初始化启动初始化器列表中的每个元素
在您的示例中,
1
和0
被隐式转换为std :: atomic_int32_t
,以及std :: atomic_int32_t
无法从std :: atomic_int32_t
中复制进行复制化。在额外的{}
版本中,很好。1
and0
aren'tstd::atomic_int32_t
s. The following works:EDIT: Why does this happen? Copy initialization kicks in for each element in the initializer list:
In your example,
1
and0
are implicitly converted tostd::atomic_int32_t
, and astd::atomic_int32_t
can't be copy-initialized from astd::atomic_int32_t
. In the extra{}
version,val_0
andval_1
are copy initialized fromstd::initializer_list<int>
s, which is fine.