问题描述
我有一个自动换行的chrono 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,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{}};
但是我需要这样做似乎很愚蠢。我不明白怎么了。我注意到以10.x开头的clang和gcc并没有抱怨隐式默认值。这仅仅是旧版gcc的编译器错误吗?还是有一种比time_point的显式默认初始化更优雅的方法?
请注意,std::atomic<std::chrono::high_resolution_clock::time_point> can not compile引用了相同的错误消息,但是询问(并获得答案)线程之间共享time_point的机制。我对此没有问题。我特别要问的是,当显式默认构造值起作用时,为什么隐式默认构造值不起作用。
解决方法
好答案@Nicol-但我要解决一个libstdc ++错误。 以下代码:
#include <atomic>
struct A {
A() {}
};
int main () {
std::atomic<A> a;
}
在gcc 8.3 / 9.x上给出了类似的错误,但在gcc 10.x上未显示错误(全部带有-std=c++17
)
clang8 + libstdc ++ 8.3也会失败。
clang + libc ++编译时没有错误。