Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

My program is simple and I want to use atomic type. It works with int or double but it doesn't work with std::string.

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

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

    return 0;
}

If I change to

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

It will give this error

/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), ^~~~~~~~~~~~~

I've tested the code with C++ 17, C++ 14 and C++ 11. Following this thread Does std::atomic<std::string> work appropriately? the atomic string should work properly, but I got this error. What's the reason behind this? And how to use std::atomic<std::string> properly?

like image 675
gameon67 Avatar asked Nov 14 '19 08:11

gameon67


1 Answers

std::string cannot be used with std::atomic as it is not TriviallyCopyable

See explanation here: 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

like image 119
Nir Avatar answered Nov 17 '22 17:11

Nir