简体   繁体   English

C ++ - 通过指针访问向量元素的安全性

[英]C++ - Safety of accessing element of vector via pointers

In a C++ project of mine, I am using a vector to hold a bunch of struct s which hold a number of elements for a simple game (ie: tic-tac-toe, coordinates, x vs o , etc). 在我的C ++项目中,我使用一个vector来保存一堆struct ,这些struct包含一些简单游戏的元素(即:tic-tac-toe,coordinates, x vs o等)。 ie: 即:

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

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. 每次在单个游戏中,每当玩家进行移动时(即:放置xo ),信息将通过push_back()存储在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. 在我的undo / redo逻辑的某些部分,我使用遍历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? 它是否安全,只要我正确管理vector ,访问它,将所有指向vector元素的指针vector ,或者存在固有风险? 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来完成同样的事情?

Thank you. 谢谢。

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). 你是正确的去关注:如果向量需要成长,在地址vector会改变(或者,如果载体缩小,但大多数实现vector不会不从程序员的一些努力缩小)。

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 ] [而不是NULL你可以使用例如-10xDEAD ]

Have you considered using the std::stack or the std::list ? 您是否考虑过使用std::stackstd::list The stack especially could be appealing for simplifying the "undo" functionality you're looking for (since the last move will always be the top of the stack). 堆栈特别有吸引力,可以简化您正在寻找的“撤消”功能(因为最后一次移动将始终是堆栈的顶部)。 But with the linked structure, you wouldn't need to worry so much about the indexing issue, though if you're tight on memory they may not be the best option... 但是使用链接结构,你不需要担心索引问题,但如果你对内存紧张,他们可能不是最好的选择......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM