【发布时间】:2018-02-17 03:22:50
【问题描述】:
似乎没有办法使用 C++14 来初始化原子成员。以下不起作用(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;
}
错误信息:
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;
}
这有效地执行零初始化,因此无法初始化为零以外的值。有没有办法初始化为其他指定的值?
【问题讨论】:
-
不要发布链接到你的编译器spew,发布spew。
-
您的第一个代码块在 VS2017 上编译时没有警告/错误,并按预期运行。我错过了什么吗?
-
@jwdonahue 如果不同的编译器不同意,那么一个是正确的,另一个是错误的。众所周知,VS 不符合标准。顺便说一句,你所说的 post the spew 是什么意思?
-
他的意思是把错误信息放在问题里。
-
你试过VS选项/std:c++14来指定你想要的语言版本吗? :-)
标签: c++ c++14 language-lawyer stdatomic aggregate-initialization