Move `unique_ptr`s between sets

半城伤御伤魂 提交于 2019-12-22 04:42:12

问题


I have two sets and an iterator to an element of a:

set<unique_ptr<X>> a, b;
set<unique_ptr<X>>::iterator iter = find something in a;

I would like to remove the element pointed by iter from a and insert it into b. Is it possible? How?


回答1:


Well, I suspect there is no normal way to do it. But there is always a non-normal one :) You can do the following:

auto tmp = const_cast<std::unique_ptr<std::string>&&>(*iter);
a.erase(iter);
b.insert(std::move(tmp));

Ok, the very first line violated set invariant and it is horrible but as far as I understand it should not be a problem since on the very next line we remove this evil node from the set.



来源:https://stackoverflow.com/questions/30048648/move-unique-ptrs-between-sets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!