gpt4 book ai didi

c++ - 关于指针的引用

转载 作者:太空狗 更新时间:2023-10-29 19:48:11 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com