为什么 std::atomic<std::string> 会给出简单的可复制错误?

Why does std::atomic<std::string> give trivially copyable error?

我的程序很简单,我想使用原子类型。它适用于 intdouble 但不适用于 std::string.

#include <iostream>
#include <atomic>
#include <string>

int main()
{
    std::atomic<int> test(0);  // works
    std::cout<<test;  // will print 0

    return 0;
}

如果我改成

std::atomic<std::string> test("0");

会报这个错误

/usr/include/c++/6/atomic: In instantiation of ‘struct std::atomic >’: main.cpp:16:34:
required from here /usr/include/c++/6/atomic:178:7: error: static assertion failed: std::atomic requires a trivially copyable type static_assert(__is_trivially_copyable(_Tp), ^~~~~~~~~~~~~

我已经用 C++ 17、C++ 14 和 C++ 11 测试了代码。在这个线程 Does std::atomic<std::string> work appropriately? 之后,原子字符串应该可以正常工作,但我遇到了这个错误。这背后的原因是什么?以及如何正确使用std::atomic<std::string>

std::string 不能与 std::atomic 一起使用,因为它不是 TriviallyCopyable

查看这里的解释: https://en.cppreference.com/w/cpp/atomic/atomic

The primary std::atomic template may be instantiated with any TriviallyCopyable type T satisfying both CopyConstructible and CopyAssignable. The program is ill-formed if any of following values is false:

https://en.cppreference.com/w/cpp/named_req/TriviallyCopyable