如何在C ++ 11中使用带有引用类型实例对象的矢量? [英] How can I use vector with a reference type instance object in C++11?

查看:149
本文介绍了如何在C ++ 11中使用带有引用类型实例对象的矢量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有可能在C ++ 11中有std :: vector没有可复制对象(有引用实例)?

Is it possible to have std::vector with no copyable object (has reference instance) in C++11 ?

struct CanNotCopy {
  int& intref_;
  CanNotCopy(int& i) noexcept : intref_(i) {}
  // How do I make move constructor and operator = ?
};

std::vector<CanNotCopy> hoge; // OK
hoge.resize(10); // default constructor required
int j = 123;
hoge[1] = CanNotCopy(j);  // copy constructor required


推荐答案

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 仍然存在。

这篇关于如何在C ++ 11中使用带有引用类型实例对象的矢量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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