Home > Software design >  Why does for cycle in vector of unique_ptr require default delete?
Why does for cycle in vector of unique_ptr require default delete?

Time:12-09

I am working in vs2019 and following code worked fine:

std::vector<Foo*> foos;
// fills vector
for (Foo* foo : foos) {
  //do stuff
}

However, if i try to use unique_ptr like this:

std::vector<std::unique_ptr<Foo>> foos;
// fills vector
for (std::unique_ptr<Foo> foo : foos) {
  //do stuff
}

then both vs and compiler are complaining (if I understand correctly) about Foo not having default delete. But std::unique_ptr<Foo> is used without problems in other parts of the codebase.

Why is this happening and how to fix/circumvent this?

CodePudding user response:

Try changing:

for (std::unique_ptr<Foo> foo : foos)

to

for (std::unique_ptr<Foo>& foo : foos)

because as mentioned in the comments by @drescherjm and @dave, the compiler should be complaining about the copy constructor being deleted (aka copying a unique_ptr is not allowed). The loop tries to copy each vector element hence the error. You can however iterate using a reference to the elements instead.

CodePudding user response:

As comments mentioned, replacing for (std::unique_ptr<Foo> foo : foos)

with for (std::unique_ptr<Foo>& foo : foos) works (probably problem with creating copies (as mentioned by @dave).

  • Related