1

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?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Lubomír Grund
  • 145
  • 1
  • 13
  • I can create vector of Foos and create unique_ptr inside the cycle, but i am still buffled why is this happening in the first place – Lubomír Grund Dec 08 '21 at 13:59
  • 5
    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 – perivesta Dec 08 '21 at 14:01
  • 1
    Change `for (std::unique_ptr foo : foos) {` to `for (std::unique_ptr& foo : foos) {` – drescherjm Dec 08 '21 at 14:02
  • you are creating coy of `std::unique_ptr` and as name indicates it should be unique. `for (auto& foo : foos)` will do the job. – Marek R Dec 08 '21 at 14:04
  • 2
    `then both vs and compiler are complaining (if I understand correctly) ...` you should always include the error message with the question. – t.niese Dec 08 '21 at 14:04

2 Answers2

1

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).

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Lubomír Grund
  • 145
  • 1
  • 13
1

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.

gsamaras
  • 71,951
  • 46
  • 188
  • 305