Search code examples
c++pointersatomic

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?


Solution

  • 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