简体   繁体   English

从空的std :: vector获取原始数据指针

[英]Get raw data pointer from empty std::vector

This is an undefined behavior: 这是一个未定义的行为:

std::vector<int> v;
int const * a = &v[0];

My goal is to avoid the UB and the vector::data() function would work. 我的目标是避免UB和vector::data()函数起作用。 But I need to do it without >=C++11 . 但是我需要在没有>=C++11

For example, if I were to allocate some memory with vector::reserve , would it work? 例如,如果我要用vector::reserve分配一些内存,那行得通吗?

v.reserve(1);
int const * a = &v[0];

Clarification: 澄清:

The vector is not changed after the point I take the pointer and the vector may be empty or contain data. 我将指针指向该点后,向量不会更改,并且向量可能为空或包含数据。

Just perform the check inside a conditional operator: 只需在条件运算符中执行检查即可:

int const * a = v.empty() ? NULL : &v[0];

This has the added benefit over data() that you can check from the pointer itself whether the vector was empty: if it was, a is null. data() ,它具有更多的好处,您可以从指针本身检查向量是否为空:如果为空,则a为null。

Vectors don't provide any guarantees of the pointers of their elements. 向量不为其元素的指针提供任何保证。 It's very dangerous to use that reserve you did, because you may push_back() some element later, which may invalidate your pointer. 使用您所做的保留是非常危险的,因为稍后您可能会在某些元素上push_back() ,这可能会使指针无效。

If you want a better story, consider that even iterators may be invalidated with push_back and erase ... why would a pointer still remain valid at all? 如果您想要一个更好的故事,请考虑一下,即使迭代器也可能因push_back擦除而失效……为什么指针仍然仍然有效?

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

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