Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 263
Plasty Grove Avatar asked Dec 23 '22 15:12

Plasty Grove


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.

like image 112
Justin Avatar answered Jan 10 '23 05:01

Justin