繁体   English   中英

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

[英]Can assignment from a const_iterator dereference cause undefined behaviour?

这段代码是我试图在其他地方做的事情的简化测试。 我有一个函数,它接受一个“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;
}

它工作并按预期打印ip = 3 ,只是我担心它可能导致未定义的行为或以其他方式导致麻烦,因为我通过分配它的取消引用参数的结果来剥离迭代器的常量。 我尝试在(1)和(2)添加const ,但它没有构建。

我有权担心吗? 如果是这样,为什么我没有收到g ++(4.9.2)的警告?

代码非常好。 你没有剥离任何常量(在C ++中没有办法隐含地这样做)。 *it给你一个const intp & 您正在将该引用引用的指针复制arg 从某些东西复制不会剥夺常数。 在你的情况下, arg的赋值分配给ip ,它不会直接绑定到容器内的intp对象。

const_iterator只是意味着你不能分配给那个迭代器和/或只能在它指向的对象上调用const函数。 复制value没有问题 - 在这种情况下是一个指针。 你不是存储const指针,如果你是,那么你必须分配一个const指针

暂无
暂无

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

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