如何从 STL 容器中获取只能移动的类型?

How to get a move-only type out of a STL container?

让我们以 std::unique_ptr<T>std::unordered_set 为例。我可以将集合中的一个元素移到别处吗?

#include <unordered_set>
#include <iostream>
#include <memory>
#include <vector>

int main()
{
    std::unordered_set<std::unique_ptr<int>> mySet;

    mySet.insert(std::make_unique<int>(1));
    mySet.insert(std::make_unique<int>(2));
    mySet.insert(std::make_unique<int>(3));

    std::vector<std::unique_ptr<int>> myVector;

    for (auto&& element : mySet)
    {
        std::cout << *element << std::endl;
        //myVector.push_back(element); won't compile as you can only get a const ref to the key
    }
}

我有一个非常实用的代码示例,我想在其中执行此操作,但不得不使用 std::shared_ptr。你知道另一个(更好的?)替代品吗?

在 C++03、C++11 和 C++14 中,不直接。您必须将类型更改为:

template <class T>
struct handle {
    mutable std::unique_ptr<T> owning_ptr;
    T* observing_ptr; // enforce that observing_ptr == owning_ptr.get() on construction

    // define operator<, hash, etc. in terms of the observing ptr
};

有了这个,你可以写:

std::unordered_set<handle<int>> mySet;
// initialize as appropriate

for (auto& elem : mySet) {
    myVector.push_back(std::move(elem.owning_ptr));        
}
mySet.clear();

这仍然是明确定义的行为,因为我们没有弄乱任何容器内部 - 观察指针在 clear() 结束之前仍然有效,只是现在 myVector 拥有它。


在C++17中,我们可以借助extract()直接更简单地做到这一点:

for (auto it = mySet.begin(); it != mySet.end();  
{
    std::cout << **it << std::endl;
    myVector.push_back(std::move(
        mySet.extract(it++).value()));
}