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()
.
解决方法
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()),则会发生未定义的行为.