c++ - 来自 const_iterator 取消引用的赋值会导致未定义的行为吗?

标签 c++ pointers pass-by-reference undefined-behavior const-iterator

此代码是对我在其他地方真正尝试做的事情的简化测试。我有一个函数,它接受一个“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,它不会直接绑定(bind)任何内容到 intp 对象容器。

关于c++ - 来自 const_iterator 取消引用的赋值会导致未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31004221/

相关文章:

java - 将数组传递给方法与将原始数据类型传递给方法不一致

c++ - CArray 内存泄漏

c++ - 如何在 c++1y 的返回类型推导中保留 cv 限定符或引用?

c++ - 继承类使用继承结构

c - 从 C 中的数组堆栈中弹出 - 将 NULL 分配给 int *

c++ - 这是使用抽象类数组 (C++) 的正确方法吗?

c++ - 如何使用宏动态加载 dll

c++ - C & C++ : What is the difference between pointer-to and address-of array?

vb.net - 'TryAction()' 方法是邪恶的吗?

kotlin - 当声明另一个变量时,可变数组将被覆盖