用BOOST_FOREACH修改std::vector中的指针

Modifying pointers in std::vector with BOOST_FOREACH

本文关键字:vector 指针 std BOOST FOREACH 修改      更新时间:2023-10-16

我有一个类node并声明为std::vector<node*>。我想使用BOOST_FOREACH来迭代向量,但是我有一个小问题。

我的代码是这样的:
data_flow_graph* dfg;
node* other_node;
[...]
BOOST_FOREACH(node* n, vector_of_nodes){
  if (n->get_id() < 100)){
    n = new node(last_id++);
    n->add_related_node(other_node);
    dfg->add_node(n);
  }
}

这是,我试图修改指针的地址,同时迭代它。问题是,虽然创建了新节点,但vector_of_nodes中的指针保持不变。我猜这是Boost如何管理对指针的访问的问题,因为如果我使用常规迭代器进行等效处理:

std::vector<node*>::iterator it;
std::vector<node*>::iterator et = vector_of_nodes.end();
for (it = vector_of_nodes.begin(); it != et; ++it){
  if ((*it)->get_id() < 100)){
    (*it) = new node(last_id++);
    (*it)->add_related_node(other_node);
    dfg->add_node(*it);
  }
}

代码运行良好,并按预期执行。

我可以用那个版本,但我很好奇…为什么第一个版本不行?

将代码改为

BOOST_FOREACH(node*& n, vector_of_nodes){
  if (n->get_id() < 100)){
    n = new node(last_id++);
    n->add_related_node(other_node);
    dfg->add_node(n);
  }
}

因为在你的版本中你改变了本地指针的地址。在使用n = new node之前,为什么不删除old呢?既然手动管理资源有问题,为什么不使用smart pointers呢?