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

Digital Marketing Facebook Marketing API 3 years ago

5.93K 1 0 0 0

_x000D_ _x000D_ 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 #include #include using std::set; using std::unique_ptr; using std::vector; void doStuff(unique_ptr ptr) { // doing stuff... } int main() { vector> ptrVector; set> 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?

User submissions are the sole responsibility of contributors, with TuteeHUB disclaiming liability for accuracy, copyrights, or consequences of use; content is for informational purposes only and not professional advice.

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 3 years ago
_x000D_ 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.
0 views
0 shares

No matter what stage you're at in your education or career, TuteeHUB will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

Similar Forum


Q

What are the best SEO tools for a personal website? What website or tools should I use to build and...

What are the best SEO tools for a personal website? What website or tools should I use to build and...
Q

Why is keyword research important?

Why is keyword research important?
Q

What is SEO ?

What is SEO ?