Is std::vector::data() reallocation-safe?

Viewed 161

As far as I know, taking a pointer or reference to std::vector element is considered bad practice. But what about std::vector::data()? Does the pointer taken by data() remain valid after reallocation?

1 Answers

As far as I know, taking a pointer or reference to std::vector element considered as bad practice.

References and pointers can avoid copying overhead, which is not a bad practice if you can ensure that the std::vector will not be reallocated during the reference or pointer lifetime.

(BTW, in C++, there is no need to use pointers when you can use references)

But what about std::vector::data()? Does the pointer taken by data() remain valid after reallocation?

No. Reallocation may cause the pointer to change. Using the old pointer after reallocation is an undefined behavior. Same for iterators.

Related