首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么std::time_point成员变量的原子不能默认构造?

为什么std::time_point成员变量的原子不能默认构造?
EN

Stack Overflow用户
提问于 2020-10-16 16:42:38
回答 1查看 698关注 0票数 3

我有一个原子包装一个time_point值。time_point的默认结构对我来说很好,所以我希望不需要显式地设置它。然而,在gcc中,我得到一个编译器错误,而没有显式设置默认值。下面是一个很小的例子:

代码语言:javascript
复制
#include <atomic>
#include <chrono>

struct A
{
    using TimePoint = std::chrono::system_clock::time_point;
    std::atomic<TimePoint> point;
};

int 
main()
{
    A a;
    return 0;
}

以下是错误消息:

代码语言:javascript
复制
<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)来解决这一问题:

代码语言:javascript
复制
std::atomic<TimePoint> point{TimePoint{}};

但我需要这么做似乎很傻。我不明白是怎么回事。我注意到clang和gcc从10.x开始并不抱怨隐性违约。这仅仅是gcc的旧版本的编译错误吗?或者,是否有比time_point的显式默认初始化更优雅的方法来处理这个问题?

请注意,std::atomic can not compile引用了同样的错误消息,但正在询问(并获得答案)线程间共享time_point的机制。我对此没意见。我特别要问的是,当显式缺省构造值确实工作时,为什么隐式缺省构造值不能工作。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-16 17:17:55

不错的答案@Nicol -但我要用一个libstdc++ bug。以下代码:

代码语言:javascript
复制
#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错误。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64393225

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档