0

I want to maintain a container (list or vector) of objects that have atomics as member variables. It seems to be creating compile errors I am not sure how to fix. The messages I see are deleted copy constructor for atomics. How can I work around that? I will need to add to the list (or vector)

#include <atomic>
#include <list>

struct S {
    std::atomic<int> n_{0};
};

int main() {
    std::list<S> l1;
    std::list<S> l2 = l1; // compile error
    std::list<std::shared_ptr<S>> l;
    S s1;
    auto ss1 = std::make_shared<S>(s1); // compile error
    
}
PrueWho
  • 53
  • 4
  • 2
    Why do you make `s1` at all? Why not just `auto ss1 = std::make_shared();` and have it construct it directly into the shared pointer? – ShadowRanger Oct 10 '22 at 22:40
  • Sounds like a dup or near-dup: https://stackoverflow.com/q/12003024/4641116 – Eljay Oct 10 '22 at 22:42

1 Answers1

0

You generally don't need the shared_ptr at all, you can construct the object directly into the list:

std::list<S> l1;
l1.emplace_back();
// l1 now has one element default-constructed

You can however not copy such a list, but it seems unlikely that you'd want that semantically anyway.

user17732522
  • 53,019
  • 2
  • 56
  • 105