访问 vector<std::unique_ptr<T> 的元素>使用迭代器? [英] Access elements of vector<std::unique_ptr<T> > using an iterator?
问题描述
我有一个类成员变量
vector
和一个成员函数,我想在其中使用 v
的 unique_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_ptr
s. 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_ptr
s without affecting ownership, simply use the de-rererence operator(s):
(*it)->someMethodOfT();
这里的解引用(*it)
是解引用迭代器,->
是解引用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> 的元素>使用迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!