C++ - 通过指针访问向量元素的安全性 [英] C++ - Safety of accessing element of vector via pointers

查看:34
本文介绍了C++ - 通过指针访问向量元素的安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个 C++ 项目中,我使用一个 vector 来保存一堆 struct ,这些 struct 保存了一个简单游戏的许多元素(即:tic-tac-toe、坐标、xo 等).即:

In a C++ project of mine, I am using a vector to hold a bunch of structs which hold a number of elements for a simple game (ie: tic-tac-toe, coordinates, x vs o, etc). ie:

struct gameMove
{
  int x;
  int y;
  int player;
  int order;
};

每次在单局游戏中,每当玩家进行移动(即:放置xo),信息都存储在向量中 通过 push_back(),创建一个撤消"功能,目前按预期工作.

Every time during a single game, whenever a player makes a move (ie: places an x or o), the information is stored in the vector via push_back(), to create an "undo" feature, which currently works as expected.

在我的撤销/重做逻辑的某些部分,我使用了遍历 vector 的函数,找到合适的元素,并直接返回指向该元素的指针.

In some parts of my undo/redo logic, I am using functions which traverse the vector, find the appropriate element, and return a pointer directly to that element.

它是否安全,只要我正确管理vector,访问它,将所有指向vector 元素的指针设为NULL,还是存在固有风险?我担心的是,如果扩展我计划做的游戏(即:对我正在处理的国际象棋游戏使用相同的代码),并且 vector 变得太大并且需要自动重新分配,指针将变得无效(即:整个列表被移动到一个新的可以容纳所有元素的连续块),或者是否有某种类型的智能指针接口到 vector 到完成同样的事情?

Is it safe, so long as I'm correctly managing the vector, access to it, NULL-ing out all the pointers that point to elements of the vector, or are there inherent risks? My concern is that if extend the game, which I plan to do (ie: use the same code for a chess game I'm working on), and that the vector gets too large and needs to be automagically re-allocated, the pointers will become invalid (ie: entire list is moved to a new contiguous block that can fit all the elements), or is there some type of smart-pointer interface to vector to accomplish the same thing?

谢谢.

推荐答案

您的担心是正确的:如果向量需要增长,vector 中的地址将会改变(或者如果向量缩小,但如果没有程序员的一些努力,vector 的大多数实现都不会缩小).

You are correct to be concerned: If the vector needs to grow, the addresses in the vector will change (or if the vector shrinks, but most implementations of vector doesn't shrink without some effort from the programmer).

直接简单的解决方案是将索引返回到向量中,而不是返回一个指针.只要它在范围内,就始终是查找特定元素的有效方法.[而不是 NULL 你可以使用例如 -10xDEAD]

The immediately simple solution would be to return the index into the vector, instead of a pointer. That, as long as it's in range, will always be a valid way to find a particular element. [And instead of NULL you could use for example -1 or 0xDEAD]

这篇关于C++ - 通过指针访问向量元素的安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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