Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can assignment from a const_iterator dereference cause undefined behaviour?

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)?

like image 696
neuviemeporte Avatar asked Jun 23 '15 13:06

neuviemeporte


2 Answers

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.

like image 74
Angew is no longer proud of SO Avatar answered Sep 30 '22 02:09

Angew is no longer proud of SO


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

like image 44
Salgar Avatar answered Sep 30 '22 03:09

Salgar