简体   繁体   English

在 C++ 中取消引用迭代器行为

[英]Dereferencing iterator behavior in C++

I'm trying to figure out why dereferencing the empty list iterator is preventing the rest of the code from running.我试图弄清楚为什么取消引用空列表迭代器会阻止代码的 rest 运行。 Comment out the line and everything seems fine, but leave it in and the program doesn't seem to get past that point.注释掉这条线,一切看起来都很好,但是把它留在里面,程序似乎没有超过那个点。

I guess it's supposed to be an error since the list is empty, but I'm not getting any warnings or errors.我想这应该是一个错误,因为列表是空的,但我没有收到任何警告或错误。

I'm using codeblocks with MinGW我正在使用 MinGW 的代码块

    std::list<std::string> slist;
    std::string word;

    auto iter = slist.begin();

    //what is this doing?
    std::cout << (*iter) << std::endl;

    while(std::cin >> word)
    {
        iter = slist.insert(iter, word);
    }

    slist.insert(slist.begin(), {"foo", "bar"});
    for(auto item: slist)
        std::cout << item << std::endl;

Well std::list is empty.那么std::list是空的。 De-referencing means you are attempting to use something that is not defined.取消引用意味着您正在尝试使用未定义的内容。 It is just wrong.这是错误的。 You should definitely not do that.你绝对不应该那样做。

You should do instead你应该这样做

for (auto i : slist)
   std::cout << i << std::endl;

which is safe.这是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM