遍历一个unique_ptr的容器 [英] Iterating over a container of unique_ptr's

查看:325
本文介绍了遍历一个unique_ptr的容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不脱离容器所有权的情况下(通过迭代器)访问容器的unique_ptr元素?当获得容器中元素的迭代器时,元素所有权是否仍在容器中?如何取消对迭代器的引用以获得对unique_ptr的访问?这样会执行unique_ptr的隐式移动吗?

How does one access unique_ptr elements of a container (via an iterator) without taking ownership away from the container? When one gets an iterator to an element in the container is the element ownership still with the container? How about when one dereferences the iterator to gain access to the unique_ptr? Does that perform an implicit move of the unique_ptr?

当我需要将元素存储在容器中(而不是按值)时,我发现我经常使用shared_ptr,即使容器在概念上拥有元素,而其他代码只是希望操作容器中的元素,因为我恐怕无法在没有所有权的情况下实际访问容器中的unique_ptr元素.

I find I'm using shared_ptr a lot when I need to store elements in a container (not by value), even if the container conceptually owns the elements and other code simply wishes to manipulate elements in the container, because I'm afraid of not being able to actually access the unique_ptr elements in the container without ownership being taken from it.

有什么见解吗?

推荐答案

只要不尝试制作unique_ptr的副本,就可以使用它.您必须像对shared_ptr那样,必须对迭代器进行双重取消引用"才能获得指针的值.这是一个简单的示例:

As long as you don't try to make a copy of the unique_ptr, you can just use it. You'll have to "double dereference" the iterator to get to the pointer's value, just as you would have to with shared_ptr. Here's a brief example:

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

template <class C>
void
display(const C& c)
{
    std::cout << '{';
    if (!c.empty())
        std::cout << *c.front();
    for (auto i = std::next(c.begin()); i != c.end(); ++i)
        std::cout << ", " << **i;
    std::cout << "}\n";
}

int main()
{
    typedef std::unique_ptr<int> Ptr;
    std::vector<Ptr> v;
    for (int i = 1; i <= 5; ++i)
        v.push_back(Ptr(new int(i)));
    display(v);
    for (auto i = v.begin(); i != v.end(); ++i)
        **i += 2;
    display(v);
}

如果您(偶然)这样做了,请复制unique_ptr:

If you do (accidentally) make a copy of the unique_ptr:

Ptr p = v[0];

然后您会在编译时发现.它不会导致运行时错误.您的用例就是构建container<unique_ptr<T>>的原因.事情应该就可以了,如果不行,问题就会在编译时而不是运行时出现.因此,不用编写代码,如果您不了解编译时错误,请在此处再次提出另一个问题.

then you'll find out at compile time. It won't cause a run time error. Your use case is why container<unique_ptr<T>> was built. Things should just work, and if they don't, the problem appears at compile time instead of run time. So code away, and if you don't understand the compile time error, then ask another question back here.

这篇关于遍历一个unique_ptr的容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆