简体   繁体   English

C ++使用指针

[英]C++ working with pointers

I don't understand why it outputs "123" even though the deletenode function set x to NULL. 我不明白为什么即使deletenode函数将x设置为NULL也会输出“ 123”。

#include <iostream>;
using namespace std;
struct node {int value; struct node *left,*right,*parent;};
void deletenode(node *a) {
    delete a;
    a=NULL;
}
int main(int argc, const char * argv[])
{
    node *x = new node;
    x->value=123;
    deletenode(x);
    if (x!=NULL) cout << x->value;
}

You have the following signature: void deletenode(node *a) . 您具有以下签名: void deletenode(node *a) You pass a pointer x to the function. 您将指针x传递给函数。 The pointer value gets copied . 指针值将被复制 Inside the function, you modify the local pointer value by writing to it via a = NULL . 在函数内部,您可以通过a = NULL写入本地指针值来修改它。

However, that modification happens on the copy. 但是,该修改发生在副本上。 The original remains unaffected. 原稿保持不受影响。 Notice that this isn't true for delete , since delete doesn't modify the pointer, it modifies (or rather, purges) the pointee . 请注意,对于delete并非如此,因为delete不会修改指针,而是会修改(或更确切地说,清除) pointee

The superficial solution is to pass the pointer value by reference: 表面的解决方案是通过引用传递指针值:

void deletenode(node*& a)

However, there's a consensus that setting pointers to nullptr (or NULL ) after deletion doesn't really help, and is therefore not normally done. 但是,有一个共识,即删除后将指针设置为nullptr (或NULL )并没有真正的帮助,因此通常无法完成。 I would therefore replace your whole call to deletenode with a simple delete x; 因此,我将用简单的delete x;替换整个对deletenode调用delete x; statement. 声明。

Although you've successfully deleted the object you intended to, the pointer itself is passed by value (copied to variable 'a') to deletenode(). 尽管您已经成功删除了想要的对象,但是指针本身通过值(复制到变量“ a”)传递给deletenode()。 So even though variable 'a' inside the function is null, variable 'x' is still pointing to the now-deleted memory. 因此,即使函数内的变量“ a”为空,变量“ x”仍指向现在已删除的内存。

因为使用delete删除实际上是将内存标记为空闲并可以重用,但是该区域的内容可能保持不变

You pass this pointer to the function BY VALUE - this means you wont see changes outside of the function. 您将此指针传递给函数BY VALUE-这意味着您将看不到函数外部的更改。 Try to pass it by reference. 尝试通过引用传递它。

#include <iostream>

template<typename T>
void destroy(T*& ptr) {
  delete ptr;
  ptr = NULL;
}

template<typename T>
struct node {
  node(T t) : value(t) { }
  ~node() {
    delete left;
    delete right;
  }
  T value;
  struct node *left,*right,*parent;
};

int main(int argc, const char * argv[]) {
  node<int> *x = new node<int>(123);

  destroy(x);

  if (x != NULL) {
    std::cout << x->value << '\n';
  }
}

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

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