Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the store to an atomic unique_ptr causing a crash?

The code compiles without issue under VC++2013 (v120) on a i7-4790 Processor (x86-64).

int main()
{
    std::atomic<std::unique_ptr<int>> p;
    p.store(std::make_unique<int>(5));
}

Once main() returns, I get a crash:

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

What's going on?

like image 276
user2296177 Avatar asked Dec 15 '22 11:12

user2296177


1 Answers

You cannot instantiate a std::atomic with a std::unique_ptr. cppreference

std::atomic may be instantiated with any TriviallyCopyable type T. std::atomic is neither copyable nor movable.

And a std::unique_ptr is not TriviallyCopyable

The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.

You could use a std::shared_ptr that does have free functions defined to allow you to have atomic stores and loads

like image 50
NathanOliver Avatar answered Dec 25 '22 22:12

NathanOliver