简体   繁体   中英

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. But I need to do it without >=C++11 .

For example, if I were to allocate some memory with vector::reserve , would it work?

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.

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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