Search code examples
c++pointersincomplete-typestdatomic

Invalid use of incomplete type (for a pointer to atomic integer variable)


When I write this,

std::atomic<int> * tmp = new std::atomic<int>();

g++ compiler returns an error saying

invalid use of incomplete type "struct std::atomic<int>"

Why is it giving this error? How can I evade this? Do I need to wrap the atomic variable inside a class and use its pointer instead?

Same thing happens with smart pointers too.

std::shared_ptr<std::atomic<int>> tmp = std::make_shared<std::atomic<int>> ();

Solution

  • incomplete type is the big clue here given by your compiler: compiler diagnostics are extremely good these days - well worth reading!

    It means you haven't #included the correct files - since the type is not complete at the point of compilation.

    Always include C++ standard library files explicitly. In this case you need <atomic> and <memory>.