c++ - 关于指针的引用

标签 c++ pointers reference

我一直在造一棵树,因为种一棵树可以拯救地球(或者只是这个项目)。

class Tree {
  Node* root;
  // ...
  void insert(int value){
    private_insert(value, root);
  }
  void insert_private(int value, node* n){
    if(n == nullptr){
      n = new node(value);
    } else {
      your standard recursive insertion function here
    }
  }
  // ...
};

长话短说,我首先尝试使用 shared_ptr,但 insert() 函数永远不会将任何元素添加到我的树中。我想我可能在共享方面做错了所以我尝试了原始指针并且我得到了相同的非插入结果。

原来我需要传递一个引用我的根/节点。

void insert_private(int value, node*& n) {...};

我明白,如果我不传递一些东西作为引用,那么就会制作一份拷贝。但是如果一个指针持有一个地址,它的拷贝不持有相同的地址吗?如果我创建一个指向非引用指针的 new() 为什么它不粘在我的根/节点上?

为什么我的问题在这里,我可以接受它是这样工作的,我的树是工作的,但我不知道为什么会这样。

编辑:阅读评论后我创建了这个小型专家级程序:

void fn(int* i){
  cout << "Address of local in fn before change: " << i << endl;
  i = new int(2);
// so basically here we made a new int, and i will get the address of 
// this integer and will point to there, what we passed on before 
// becomes irrelevant
  cout << "Address of local in fn after change: " << i << endl;
}
void fn2(int **i){
  cout << "Address of local in fn2 before change: " << i << endl;
  *i = new int(2);
  cout << "Address of local in fn2 after change: " << i << endl;
}
int main(){
  int* p = nullptr;
  cout << "Address of p: " << p << endl;
  fn(p);
  cout << "p& is: " << &p << endl;
  fn2(&p);

  cin.get();
  return 0;
};

谢谢大家的解答,帮助很大。 random.org 将确定谁将获得批准的答案。

最佳答案

是的,它是一个拷贝,它拥有相同的地址,但您只分配给拷贝,然后在函数返回时将其丢弃。原文不变。那是你的问题。

顺便说一句,恕我直言,如果您要更改参数的值,则应该使用指针,因此在您的情况下是指向指针的指针。这让读者更清楚地知道您正在更改值。

关于c++ - 关于指针的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31408111/

相关文章:

c++ - Flex/Bison 评估不正确

c++是否在需要时将引用隐式转换为值?

java - Java 中 Integer 对象的比较运算符的安全性

c++ - PIMPL 习惯用法,用于指向 C++ 中的类

c++ - Position 2D array bug as parameter 导致内存转储

C多维数组指向问题?

C++ 逗号运算符重载和引用 vector

c++ - 将 null 从 C++/CLI 发送到托管 C#

C++ 是否应该在基类中声明派生类中的公共(public)数据字段?

c++ - 在显示二进制数据时如何停止我的 Windows 控制台应用程序触发蜂鸣声