简体   繁体   English

const_iterator dereference的赋值是否会导致未定义的行为?

[英]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. 我有一个函数,它接受一个“ref-to-ptr”参数并修改它以从指针列表返回一个指针。

#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. 它工作并按预期打印ip = 3 ,只是我担心它可能导致未定义的行为或以其他方式导致麻烦,因为我通过分配它的取消引用参数的结果来剥离迭代器的常量。 I tried to add const at (1) and (2) but it didn't build. 我尝试在(1)和(2)添加const ,但它没有构建。

Am I right to be worried? 我有权担心吗? If so, why am I not getting a warning from g++ (4.9.2)? 如果是这样,为什么我没有收到g ++(4.9.2)的警告?

The code is perfectly fine. 代码非常好。 You're not stripping away any constness (there's no way to do that implicitly in C++). 你没有剥离任何常量(在C ++中没有办法隐含地这样做)。 *it gives you a const intp & . *it给你一个const intp & You're copying the pointer referred to by that reference into arg . 您正在将该引用引用的指针复制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. 在你的情况下, arg的赋值分配给ip ,它不会直接绑定到容器内的intp对象。

const_iterator just means you can't assign to that iterator and/or can only call const functions on the object it points to. const_iterator只是意味着你不能分配给那个迭代器和/或只能在它指向的对象上调用const函数。 There is no problem with you copying the value - in this case a pointer. 复制value没有问题 - 在这种情况下是一个指针。 You are not storing const pointers, if you were, then you would have to assign to a const pointer 你不是存储const指针,如果你是,那么你必须分配一个const指针

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

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