Is it safe to use the structure dereference operator (->) on the result of std :: atomic :: load

When trying to work with the std atomic pointer, I came across the following. Let's say I do this:

std::atomic<std::string*> myString;
// <do fancy stuff with the string... also on other threads>

//A can I do this?
myString.load()->size()

//B can I do this?
char myFifthChar = *(myString.load()->c_str() + 5);

//C can I do this?
char myCharArray[255];
strcpy(myCharArray, myString.load()->c_str());

I am sure that C is illegal, since myString can be deleted in the meantime.

However, I am not sure about B. I believe that they are illegal, because the pointer may be delayed during the read operation.

However, if this is the case, how can you read from an atomic pointer that can be deleted. Since the load is 1 step, and reading the data is 1 step.

+4
source share
4 answers

, - . : std::shared_ptr<const std::string> shared_ptr atomic_load atomic_store. std::shared_ptr , , ( ) , , const, , .

EDIT: , " ": std::atomic<std::string *>, , .

// Data
std::atomic<std::string *> str(new std::string("foo"));

// Thread 1
std::cout << *str.load();

// Thread 2
*str.load() = "bar"; // race condition with read access in thread 1

// Thread 2 (another attempt using immutable instances)
auto newStr = new std::string("bar");
auto oldStr = str.exchange(newStr);
delete oldStr;  /* race condition with read access in thread 1
                   because thread 1 may have performed load() before
                   the exchange became visible to it, and may not
                   be finished using the old object. */

, operator <<, size() 1 .

"", sleep delete , 1 . , ( "-", ++) , , rsp. .

+2
// A can I do this?
myString.load()->size()

, , , - / string, myString . , , std::string, , , ...

, load / string, , myString, string, load ed - . , memory_order load(). , , / .

, , myString() string a, b, c, &b... string b isn ' t /, size(), . , myString() , c / / b .size().

, , load() , b /, , , , /. , ​​ (, - /, //, ...), (, , b, , LRU .

- cycling myString static const string, / (, / main()).

// B can I do this?
char myFifthChar = *(myString.load()->c_str() + 5);

, .

// C can I do this?
char myCharArray[255];
strcpy(myCharArray, myString.load()->c_str());

, ( , ).

, C , myString .

- , , C, , , , , .

+4

, C , myString .

. , - - - . , . , .

- , std::shared_ptr<T>, , , .

+3

string, .

atomic , , .

+2

All Articles