取消引用字符串向量的 .end() 时的行为
Behavior when dereferencing the .end() of a vector of strings
我想知道通过取消引用 string
s 的vector
的端外iterator
,将string
设置为等于返回的任何内容是否"安全"。当我运行程序时
#include <vector>
#include <string>
int main()
{
std::vector<std::string> myVec;
std::cout << *myVec.end();
return 0;
}
我收到以下错误。
/usr/local/lib/gcc/i686-pc-linux-gnu/4.1.2/../../../../include/c++/4.1.2/debug/safe_iterator.h:181:
error: attempt to dereference a past-the-end iterator.
Objects involved in the operation:
iterator "this" @ 0x0xffdb6088 {
type = N11__gnu_debug14_Safe_iteratorIN9__gnu_cxx17__normal_iteratorIPSsN10__gnu_norm6vectorISsSaISsEEEEEN15__gnu_debug_def6vectorISsS6_EEEE (mutable iterator);
state = past-the-end;
references sequence with type `N15__gnu_debug_def6vectorISsSaISsEEE' @ 0x0xffdb6088
}
Disallowed system call: SYS_kill
您可以在 http://codepad.org/fJA2yM30 查看它
我想知道这一切的原因是因为我的代码中有一个片段,就像
std::vector<const std::string>::iterator iter(substrings.begin()), offend(substrings.end());
while (true)
{
this_string = *iter;
if (_programParams.count(this_string) > 0)
{
this_string = *++iter;
我想确保如果++iter
等于offend
,就不会发生奇怪的事情.
你说:
我想知道通过取消引用字符串向量的场外迭代器将字符串设置为等于返回的任何字符串是否"安全"
不,这不安全。从 http://en.cppreference.com/w/cpp/container/vector/end
将迭代器返回到容器最后一个元素之后的元素。
此元素充当占位符;尝试访问它会导致未定义的行为。
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- 为什么在使用 auto&&it=--vec.end(),是 UB 时自动推导左值引用?
- begin() 和 end() 不应该只对类的 l 值引用进行调用吗?
- 迭代器:如果 '*' 返回元素的引用,为什么删除 *(myList.end()) 会给出 SegFault
- 向量迭代器对于包装器类不可取消引用(没有超出 end() 取消引用)
- 为什么BOOST.RANGE RANGE_BEGIN/END FREE功能对const和非const引用都重载
- 取消引用字符串向量的 .end() 时的行为
- 在“abcd”和“abc”的情况下,“std::equal”是否取消引用“end()”
- 引用从end()中减去的std::向量的一部分可以吗
- Qt容器(QVector,QList)::end()返回一个无法引用的迭代器
- 为什么stl_tree.h中的end()返回对迭代器对象的引用,而begin()返回object ?
- 对end()解引用安全吗?
- 当有人取消引用我的 end() 迭代器时,我该怎么办