Can assignment due to dereferencing const_iterator cause undefined behavior?

This code is a simplified test for what I'm trying to do elsewhere. I have a function that 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 it bothers me that it can cause undefined behavior or otherwise lead to problems, because I remove the iterator constant, assigning the result of its dereference to Argument. I tried adding const to (1) and (2) but did not create one.

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

+5
source share
2 answers

The code is great. You do not remove any constant (there is no way to do this implicitly in C ++). *it gives you const intp & . You copy the pointer that this link refers to in arg . Copying from something does not separate the continent. The arg assignment is assigned to ip in your case, it does not bind anything to the intp object inside the container.

+5
source

const_iterator simply means that you cannot assign this iterator and / or you can only call const functions on the object it points to. There is no problem copying value - in this case a pointer. You do not save constant pointers; if you were, you would need to assign a const pointer

+2
source

All Articles