访问 vector<std::unique_ptr<T> 的元素&gt;使用迭代器? [英] Access elements of vector&lt;std::unique_ptr&lt;T&gt; &gt; using an iterator?

查看:83
本文介绍了访问 vector<std::unique_ptr<T> 的元素&gt;使用迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类成员变量

vector>v;

和一个成员函数,我想在其中使用 vunique_ptr 元素,由 iterator 参数寻址".哪一个更好?

and a member function where I want to use a unique_ptr element of v "addressed" by an iterator argument. Which one is better?

void mem_fun(vector<std::unique_ptr<T> >::iterator it) {
    std::unique_ptr<T> p;
    p = std::move(*it);
    ...
}

void mem_fun(vector<std::unique_ptr<T> >::iterator it) {
    std::unique_ptr<T>& p = *it;
    ...
}

据我所知,第二种方式似乎违反了 unique_ptr 的唯一性".但是 std::move() 可以移动 *it (参考)吗?顺便说一句,谁真正拥有 unique_ptr 指针、类、成员向量、任何成员函数,或者其他什么?

From what I know, it seems the second way just kind of violates the "uniqueness" of unique_ptr. But can std::move() move *it (a reference)? BTW, who truly owns the unique_ptr pointers, the class, the member vector, any member function, or what else?

推荐答案

第一个版本取得 unique_ptr 目标的所有权,并留下空的 unique_ptr 向量.这不太可能是您想要的.第二个版本令人困惑.如果您只想在不影响所有权的情况下访问由 unique_ptr 管理的对象,只需使用 de-rerence 运算符:

The first version takes ownership of the unique_ptr's target and leaves the vector with empty unique_ptrs. It is unlikely that this is what you want. The second version is confusing. If all you want to do is access the objects managed by the unique_ptrs without affecting ownership, simply use the de-rererence operator(s):

(*it)->someMethodOfT();

这里的解引用(*i​​t)是解引用迭代器,->是解引用unique_ptr.

Here, the de-reference (*it) is to de-reference the iterator, and the -> is to de-reference the unique_ptr.

记住:unique_ptr 的唯一性"是指它的所有权.没有什么可以说托管对象不能被许多非所有者访问.但由您决定谁拥有所有权,具体取决于您的应用程序要求.

Remember: the "uniqueness" of a unique_ptr refers to its ownership. There's nothing to say the managed object can't be accesses by many non-owners. But it is up to you to decide who takes ownership, depending on the requirements of your application.

这篇关于访问 vector<std::unique_ptr<T> 的元素&gt;使用迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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