In C++, why does auto not work with std::atomic?

Viewed 176

General recommendation online seems to be to use auto where possible.

But this doesn't work:

auto cnt = std::atomic<int>{0};

While this works fine:

std::atomic<int> cnt {0};

Is there a recommended way to use this with auto? Or should I just assume that auto is not possible with this?

1 Answers

std::atomic is immovable because it has a deleted copy constructor. Prior to C++17, auto cnt = std::atomic<int>{0}; tries to call the move constructor to move the temporary into cnt, so you can't use std::atomic with almost always auto.

C++17 brought us mandatory copy elision, so auto cnt = std::atomic<int>{0}; works fine, not calling any move constructor but instead initializing the object in-place.

Related