簡體   English   中英

為什么不能默認構造 std::chrono time_point 成員變量的 std::atomic ?

[英]Why can't a std::atomic of a std::chrono time_point member variable be default constructed?

我有一個原子包裝一個計時 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

這是一個 Godbolt 鏈接: 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> 無法編譯引用相同的錯誤消息,而是詢問(並獲得答案)線程之間共享 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++ 編譯沒有錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM