Can assignment from a const_iterator dereference cause undefined behaviour?

845 views Asked by At

This code is a simplified test for something I am trying to do for real elsewhere. I have a function which takes a "ref-to-ptr" argument and modifies it to return a pointer from a list of pointers.

#include <iostream>
#include <list>
using namespace std;

typedef int* intp;
typedef std::list<intp> intplist;
intplist myList;

void func(intp &arg) // (1)
{
    intplist::const_iterator it = myList.begin();
    std::advance(it, 2);
    arg = *it;
}

int main()
{
    myList.push_back(new int(1));
    myList.push_back(new int(2));
    myList.push_back(new int(3));

    int* ip = NULL; // (2)
    func(ip);
    if (ip) cout << "ip = " << *ip << endl;
    else cout << "ip is null!" << endl;

    for (intplist::const_iterator it = myList.begin(); it != myList.end(); ++it) 
        delete *it;
    return 0;
}

It works and prints ip = 3 as expected, only I am worried that it may be causing undefined behaviour or otherwise lead to trouble, because I am stripping away the constness of the iterator by assigning the result of it's dereferencing to the argument. I tried to add const at (1) and (2) but it didn't build.

Am I right to be worried? If so, why am I not getting a warning from g++ (4.9.2)?

2

There are 2 answers

3
Angew is no longer proud of SO On BEST ANSWER

The code is perfectly fine. You're not stripping away any constness (there's no way to do that implicitly in C++). *it gives you a const intp &. You're copying the pointer referred to by that reference into arg. Copying from something does not strip constness away. The assignment to arg assigns into ip in your case, it does not bind anything diretly to the intp object inside the container.

0
Salgar On

const_iterator just means you can't assign to that iterator and/or can only call const functions on the object it points to. There is no problem with you copying the value - in this case a pointer. You are not storing const pointers, if you were, then you would have to assign to a const pointer