Why can I not move unique_ptr from a set to a function argument using an iterator?
Asked Answered
A

2

6

I have a set of unique_ptr instances and want to pass all of them as an argument to a function. Example demonstrated by below code.

#include <memory>
#include <set>
#include <vector>

using std::set;
using std::unique_ptr;
using std::vector;

void doStuff(unique_ptr<int> ptr)
{
  // doing stuff...
}

int main()
{
  vector<unique_ptr<int>> ptrVector;
  set<unique_ptr<int>> ptrSet;

  for (auto cur = ptrVector.begin(); cur != ptrVector.end(); cur++)
  {
    doStuff(std::move(*cur));
  }

  for (auto cur = ptrSet.begin(); cur != ptrSet.end(); cur++)
  {
    doStuff(std::move(*cur));
  }

  return 0;
}

This results in the following compiler error (GCC 4.8.1):

uptrfncall.cpp: In function ‘int main()’:
uptrfncall.cpp:27:25: error: use of deleted function ‘std::unique_ptr::unique_ptr(const std::unique_ptr&) [with _Tp = int; _Dp = std::default_delete]’
  doStuff(std::move(*cur)); // line 25, compiler error
                         ^
In file included from /usr/include/c++/4.8/memory:81:0,
                 from uptrfncall.cpp:1:
/usr/include/c++/4.8/bits/unique_ptr.h:273:7: error: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^
uptrfncall.cpp:9:10: error:   initializing argument 1 of ‘void doStuff(std::unique_ptr)’
     void doStuff(unique_ptr ptr)
          ^

Note that it works flawlessly for the vector but not for the set. As the set is not const, the begin() call should not return a const_iterator so it should be possible to move the values when dereferencing the iterator. Why does this not compile?

Adjustment answered 13/8, 2013 at 5:35 Comment(0)
K
11

The set may not be const, but the elements within it are. You cannot modify a set's elements, as it wouldn't be able to guarantee it's maintaining its invariants.

Kendyl answered 13/8, 2013 at 5:40 Comment(3)
Then what is the difference between set::iterator and set::const_iterator if I can never modify the elements anyway?Adjustment
@Chris: For conformance with the other containers, it has both names. They are, however, the same.Kendyl
But see open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3645.pdf for a proposal (not accepted) on how this could be done.Methylal
E
1

Code line std::set is created basing on Red-Black tree and set's iterator type is same as tree's key type, obviously you cannot change key's value.

Enfeoff answered 12/12, 2018 at 7:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.