c++ - 迭代器生命周期

标签 c++ vector iterator lifetime

所以情况是这样的:

vector <string>::iterator * it;
{
    vector <string> v{"asd", "asd"};
    auto iter = v.begin();
    it = new vector <string>::iterator(iter);
}
(**it) = string("asd");

现在,我在网络上找不到任何资源来告诉我这是否是 UB 或者是否是有效的代码。

我的问题是:
当我创建迭代器时,如果该迭代器的生命周期比引用的容器长,那么这是未定义的行为还是在标准中的某个位置定义了?

最佳答案

在您发布的代码中,

(**it) = string("asd");

导致未定义的行为。

*iter 是一个迭代器,但当您到达该行时,相应的 vector 已不存在。因此,**iter 类似于取消引用悬空指针。顺便说一句,如果您仅使用迭代器而不是迭代器*,这一点不会改变。

以下代码也会导致未定义的行为。

vector <string>::iterator it;
{
    vector <string> v{"asd", "asd"};
    auto iter = v.begin();
    it = iter;
}
(*it) = string("asd");

关于c++ - 迭代器生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61195804/

相关文章:

c++ - 将 gSOAP 与 2 个不同的 wsdl 文件一起使用时出现链接器错误

C++ vector 字面量,或类似的东西

iterator - 为什么看起来我可以使用不可变 BTreeMap 中的值?

c++ - (string&)string() 和 (string& )""作为默认参数有什么区别?

c++ - 为什么插入 map<int, int> 失败?

c++ - 特殊协议(protocol)的 apache httpd 扩展帮助

在 C++11 中调用 C 函数时,我可以将 std::vector 作为 FILE* 潜入吗?

c++ - Visual Studio 2010,C++,vector.clear() 期间的 "vector iterators Incompatible"

c++ - 在 C++ 中访问列表列表的元素

python - 'any()' 调用后不保留迭代器值