引用对象的向量 [英] Vectors of references to objects

查看:107
本文介绍了引用对象的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个引用对象的向量是合法的,如下面的对象?

 向量< Agent&见过

这将例如由场景中的一些而不是所有对象填充? p>

我有一个Agent对象的向量,但是上面列出的向量应该只包含每个代理当前可以看到的引用 - 这意味着引用将被添加和删除时间。



这是语言允许的东西吗?此外,还有什么我需要知道吗?如果我从向量中删除引用它会永久存在吗?是否是内存泄漏?



我似乎在声明该向量的行上收到此错误:

 错误C2528:'pointer':引用的指针是非法的

这是直接与线或是最可能发生在别的地方吗?它正在构造函数初始化列表中初始化为这样:

  seenAgents(vector< Agents&>())


解决方案

您不能拥有作为参考,不是可复制可分配和所有 STL容器应该存储可复制可分配项目。



但是你可以让容器保存指针。像这样:

  vector<代理*>见过

这有点危险。您需要确保这些指针将保持有效。我的意思是 - 如果有人删除一个对象,指针在这个容器中的指针,指针变得无效。你需要确保这不会发生,因为你不能检查它(你不能检查 NULL ,因为指针不会变成<$ c $



这里的最佳解决方案(由带有指针的容器提供)将是使用一些智能指针 - 一些具有引用计数,例如;它们将保证对象将存在并且指针有效。如果智能指针指向的对象被销毁,你可以检查 NULL


Is it legal to have a vector of references to objects, like the following?

vector<Agent&> seenAgents;

Which would for example be populated by some, but not all of the objects in the scene?

I have a vector of Agent objects, but the vector outlined above should hold references to only the ones each agent can currently see - meaning that the references will be being added and removed all the time.

Is this something the language will allow? And in addition, is there anything else I need to be aware of? If I remove a reference from the vector does it persist anywhere? Is it a memory leak?

I seem to be getting this error on the line declaring the vector:

error C2528: 'pointer' : pointer to reference is illegal

Is this something directly to do with the line or is it most likely occurring somewhere else? It's being initialised in the constructors initialiser list like this:

seenAgents(vector<Agents&>())

解决方案

You can't have vector of references, as a reference is not copyable assignable and all STL containers are supposed to store copyable assignable items.

But you can make the container to hold pointers. Like this:

vector< Agents* > seenAgents;

This is a little dangerous. You need to be sure that these pointers will remain valid. I mean - if someone deletes an object, pointed by a pointer in this container, the pointer becomes invalid. You need to be sure that this will not happen, because you can't check it (you can't check for NULL, because a pointer will not become NULL, if someone deletes the pointed object).

The best solution here (provided by container with pointers) would be to use some smart pointers - some with reference count, for example; they will guarantee you that the object will exist and that the pointer is valid. And in case that the object, pointed by the smart pointer, is destroyed, you can check it for NULL.

这篇关于引用对象的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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