且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C ++ 11中使用带有引用类型实例对象的矢量?

更新时间:2021-12-10 23:17:03

http://en.cppreference.com/w/cpp/container/vector> std :: vector ,描述 T

From std::vector, describing T:


对元素施加的要求取决于对容器执行的实际操作。一般来说,要求元素类型满足MoveConstructible和MoveAssignable的要求,但是许多成员函数强加了更严格的要求。

The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type meets the requirements of MoveConstructible and MoveAssignable, but many member functions impose stricter requirements.

CanNotCopy 不可移动或可复制,因此不能用作 T

CanNotCopy is not moveable, or copyable, so cannot be used as T.

部分解决方案是使用 std :: reference_wrapper< CanNotCopy>

A partial solution is to use std::reference_wrapper<CanNotCopy> as the element type (which is copyable but not default constructible) which:


...是一个在可复制,可分配对象中包装引用的类模板。它经常被用作将引用存储在不能正常保存引用的标准容器(如std :: vector或std :: pair)中的机制。

...is a class template that wraps a reference in a copyable, assignable object. It is frequently used as a mechanism to store references inside standard containers (like std::vector or std::pair) which can not normally hold references.

例如:

std::vector<std::reference_wrapper<CanNotCopy>> hoge;
int j = 19;
CanNotCopy c(j);
hoge.push_back(std::ref(c));
std::cout << hoge[0].get().intref_ << "\n";

resize() c $ c> std :: reference_wrapper< CanNotCopy> ,因为它不是默认可构造的。然而,这个解决方案很脆弱,因为 CanNotCopy 引用了和 c 在 CanNotCopy 实例中引用,存在悬挂引用的风险。

resize() is unavailable with std::reference_wrapper<CanNotCopy> because it is not default constructible. However, this solution is fragile as there are lifetime dependencies on the CanNotCopy referenced and the int referenced within the CanNotCopy instance, running a risk of dangling references.

解决方案是使用 std :: unique_ptr< CanNotCopy> 作为元素类型它是可移动的和默认构造的):

A solution is to use std::unique_ptr<CanNotCopy> as the element type (which is moveable and default constructible):

std::vector<std::unique_ptr<CanNotCopy>> hoge;
hoge.resize(5);
int j = 19;
hoge[1].reset(new CanNotCopy(j));
std::cout << hoge[1]->intref_ << "\n";

int CanNotCopy 仍然存在。