c – 有一个指向保留向量元素的指针是否合法?

前端之家收集整理的这篇文章主要介绍了c – 有一个指向保留向量元素的指针是否合法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我很好奇,如果这样的事情是合法的:
std::vector<some_class_type> vec;
vec.reserve(10);
some_class_type* ptr = vec.data() + 3; // that object doesn't exist yet

请注意,我没有尝试访问指向的值.

这是标准对data()的说明,但我不确定它是否相关:

Returns: A pointer such that [data(),data() + size()) is a valid
range. For a non-empty vector,data() == &front().

解决方法

您提供的示例不显示任何立即未定义的行为.根据标准,因为您保留的元素的数量大于矢量的当前容量,将会进行重新分配.由于分配发生在保留被调用的位置,所以data()返回的指针本身是有效的.

23.3.6.3/2(重点是我的)

Effects: A directive that informs a vector of a planned change in size,so that it can manage the storage allocation accordingly. After reserve(),capacity() is greater or equal to the argument of reserve if reallocation happens; and equal to the prevIoUs value of capacity() otherwise. Reallocation happens at this point if and only if the current capacity is less than the argument of reserve()@H_403_26@. If an exception is thrown other than by the move constructor of a non-CopyInsertable type,there are no effects.

然而,如果您在添加足够的元素之前尝试取消引用指针,其中指针位于data()size()之外,或者如果添加多于capacity()),则会发生未定义的行为.

猜你在找的C&C++相关文章