c++ - 为什么不能默认构造 std::chrono time_point 成员变量的 std::atomic?

标签 c++ c++-chrono stdatomic

我有一个原子包装一个 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, 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{}};

但我需要那样做似乎很愚蠢。我不明白哪里出了问题。我注意到从 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++ 编译无错误。

关于c++ - 为什么不能默认构造 std::chrono time_point 成员变量的 std::atomic?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64393225/

相关文章:

c++ - 将 minutes::rep 转换为 hours::rep

c++ - 如何使用 chrono 返回持续时间类型

c++ - 在 map 中就地构建不可 move 的对象

multithreading - 读取另一个线程中的变量

c++ - 这些是 C++ 中允许的优化吗?

c++ - 读取十六进制值在 C++ 中给出了错误的数字

MySQL 的 C++ 连接器

c++ - 在 C++ 中使用 FFmpeg 覆盖视频帧

c++ - 非恢复浮点平方根算法

c++ - 具有空定义的模板特化