简体   繁体   English

使用unique_ptr向量的原始指针作为ID进行排序

[英]Using raw pointers from vector of unique_ptr as an ID for sorting

I'd love to ask if this is a good practice. 我想问一下这是否是一个好习惯。 Let's assume this scenario: 让我们假设这种情况:

std::vector<unique_ptr<Model>> data;

Is it safe to work with the raw pointers from this vector (raw pointer from each unique_ptr in the vector)? 使用此向量的原始指针(向量中每个unique_ptr的原始指针)是否安全? I understand that the vector might reallocate the data when exceeding the reserved space but that would affect only the addresses of the unique_ptr while the inner raw pointer is guaranteed to stay the same right? 我知道向量可能会在超过保留空间时重新分配数据,但这只会影响unique_ptr的地址,而内部原始指针却保证保持不变?

Therefore, is it safe to identify the models by using those raw pointers instead of adding some id members? 因此,通过使用这些原始指针而不添加一些id成员来标识模型是否安全?

More concretely, is it OK to use those raw pointers as keys in a map? 更具体地说,可以将这些原始指针用作映射中的键吗? I need to sort objects which contain a model pointer (as a member) from the vector and make groups of the objects with the same models. 我需要对向量中包含模型指针(作为成员)的对象进行排序,并使用相同的模型对对象进行分组。

I know I can use some handles like indexes into the vector or unique IDs but that would be a useless overhead probably. 我知道我可以使用一些句柄,例如向量的索引或唯一的ID,但这可能是无用的开销。 The reason I am asking is that depending on pointer address feels somehow unsafe to me :-) 我问的原因是,取决于指针地址对我来说有点不安全:-)

Yep! 是的! That's fine :) 没关系 :)

Just make sure that the objects outlive their pointers, as usual. 像往常一样,只需确保对象的寿命超过其指针即可。

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

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