I am reading through Anthony Williams' "C++ Concurrency in Action" and in Chapter 5, which talks about the new multithreading-aware memory model and atomic operations, and he states:
In order to use std::atomic<UDT>
for some user-defined UDT
, this type must have a trivial copy assignment operator.
As I understand it, this means that we can use std::atomic<UDT>
if the following returns true:
std::is_trivially_copyable<UDT>::value
By this logic, we shouldn't be able to use std::string
as a template argument for std::atomic
and have it work correctly.
However, the following code compiles and runs with expected output:
#include <atomic>
#include <thread>
#include <iostream>
#include <string>
int main()
{
std::atomic<std::string> atomicString;
atomicString.store( "TestString1" );
std::cout << atomicString.load() << std::endl;
atomicString.store( "TestString2" );
std::cout << atomicString.load() << std::endl;
return 0;
}
Is this a case of undefined behaviour which just happens to behave as expected?
Thanks in advance!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…