0

I have a function which is like

for (auto&& i : v) {
    ...
    this->fifoQueue.push_back(move(i.p));
    ...
}

where fifoQueue is of type vector<unique_ptr<T> >, v is of type vector<struct s>, and struct s is

struct s {
    ...
    std::unique_ptr<T> p;
    ...
};

The statement this->fifoQueue.push_back(move(i.p)); has caused a compiler error "... error: declared here unique_ptr(const unique_ptr&) = delete; ...". What's wrong with this statement?

I have another working statement basically the same as it, except that statement is like this->fifoQueue.push_back(move(p)). So i.p is the evil? Or auto&&?


Update:

As Petr inferred, v is indeed a const reference, which caused the error.

vincentvangaogh
  • 354
  • 3
  • 11

2 Answers2

3

(Expanding my comment)

Your error message, unique_ptr(const unique_ptr&), seems to indicate that i.p becomes const, thus push_back has to make its copy (or in fact even std::move has to make its copy, see this answer). However, unique_ptr can not be constructed as a copy of const unique_ptr&, because this is absolutely senseless given the nature of unique_ptr. So you should look where does it become const from.

I thought the most probable source of this constness is from v, because you have not shown us that declaration.

Community
  • 1
  • 1
Petr
  • 9,812
  • 1
  • 28
  • 52
0

As said above, seems like compiler wants to make a copy of your struct. Because of this unique_ptr inside it cannot.

When you think about it, gues what would mean auto here? It would be rather yourStruct & than yourStruct, because you can actually modify the struct inside this vector. And bacause of reference collapsing you get yourStruct & from auto &&.

All in all, instead of thinking how to avoid this situation with push_back simply use emplace_back which enforces construction inside vector.

Community
  • 1
  • 1
bartop
  • 9,971
  • 1
  • 23
  • 54