我有一个原子包装一个time_point值。time_point的默认结构对我来说很好,所以我希望不需要显式地设置它。然而,在gcc中,我得到一个编译器错误,而没有显式设置默认值。下面是一个很小的例子:
#include <atomic>
#include <chrono>
struct A
{
using TimePoint = std::chrono::system_clock::time_point;
std::atomic<TimePoint> point;
};
int
main()
{
A a;
return 0;
}以下是错误消息:
<source>: In function 'int main()':
<source>:13:7: error: use of deleted function 'A::A()'
A a;
^
<source>:6:5: note: 'A::A()' is implicitly deleted because the default definition would be ill-formed:
A() = default;
^
<source>:6:5: error: use of deleted function 'constexpr std::atomic<_Tp>::atomic() [with _Tp = std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1, 1000000000> > >]'
In file included from <source>:1:
/opt/compiler-explorer/gcc-8.3.0/include/c++/8.3.0/atomic:194:7: note: 'constexpr std::atomic<_Tp>::atomic() noexcept [with _Tp = std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1, 1000000000> > >]' is implicitly deleted because its exception-specification does not match the implicit exception-specification ''
atomic() noexcept = default;
^~~~~~
Compiler returned: 1这里有一个天栓链接:https://godbolt.org/z/YocxGd
我可以通过简单地显式添加默认初始化(https://godbolt.org/z/8z5WqW)来解决这一问题:
std::atomic<TimePoint> point{TimePoint{}};但我需要这么做似乎很傻。我不明白是怎么回事。我注意到clang和gcc从10.x开始并不抱怨隐性违约。这仅仅是gcc的旧版本的编译错误吗?或者,是否有比time_point的显式默认初始化更优雅的方法来处理这个问题?
请注意,std::atomic can not compile引用了同样的错误消息,但正在询问(并获得答案)线程间共享time_point的机制。我对此没意见。我特别要问的是,当显式缺省构造值确实工作时,为什么隐式缺省构造值不能工作。
发布于 2020-10-16 17:17:55
不错的答案@Nicol -但我要用一个libstdc++ bug。以下代码:
#include <atomic>
struct A {
A() {}
};
int main () {
std::atomic<A> a;
}在gcc 8.3/9.x上给出了一个类似的错误,但在gcc 10.x上编译了w/o错误(全部用-std=c++17)
clang8 + libstdc++ 8.3也失败了。
clang + libc++编译w/o错误。
https://stackoverflow.com/questions/64393225
复制相似问题