加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 06:04:25 所属栏目:百科 来源:网络整理
导读:我很好奇,如果这样的事情是合法的: std::vectorsome_class_type vec;vec.reserve(10);some_class_type* ptr = vec.data() + 3; // that object doesn't exist yet 请注意,我没有尝试访问指向的值. 这是标准对data()的说明,但我不确定它是否相关: Returns:
我很好奇,如果这样的事情是合法的:
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(). If an exception is thrown other than by the move constructor of a non-CopyInsertable type,there are no effects.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读