简体   繁体   中英

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. 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

    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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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