【问题标题】:Do pointers get deallocated?指针会被释放吗?
【发布时间】:2020-06-29 21:59:48
【问题描述】:
void test(int pnt)
{ 
  int* p = &pnt; //can a pointer get deallocated?
  return;
}

在这种情况下可以删除指针吗? 我不知道他们有没有。但我确实知道,如果你从免费存储中获得一个指针,它不会被释放。

【问题讨论】:

  • 指针本身是一个自动变量,它的内存将在作用域结束时被释放。如果你这样做:{ int* p = new int; } 那么p 的内存将被释放,但不会释放它指向的int。但是,在您的函数中,pnt 也是自动的,将被自动释放。
  • @TedLyngmo 所以如果 p 指向 new int 那么 p 会被删除,而不是 new int
  • 您只能使用delete 使用new 创建的对象。 delete 的每次使用都必须与 new 的一次使用完全匹配。这里没有使用new 创建对象,所以没有什么需要是deleted。你不要delete指针;你delete指针指向的对象。
  • @doggo Deleted 可能不是正确的词,但p 占用的内存将被释放,而不是int 占用的内存。
  • 指针只是一个普通的、旧的常规变量,具有通常的生命周期规则。它的值恰好是某个其他对象的地址(或者什么都没有,并且指针无法确定)。

标签: c++


【解决方案1】:

指针ptest 函数中的一个局部变量,所以当函数返回时它会被释放。

参数pnt 也是test 函数中的一个局部变量,所以它在函数返回时被释放。

如果你从函数返回&pnt,它会在函数返回之后是一个悬空指针,因为变量pnt会被销毁。

int* test(int pnt) {
    return &pnt; // bad idea, but technically you haven't done anything wrong yet
}

void test2() {
    int* p = test(5);
    cout << *p; // accesses a deallocated variable. Bad stuff happens here
}

如果你返回了p,而p没有指向一个局部变量,那很好,因为它指向的东西并没有被破坏,而指针变量本身是不相关,因为它只是暂时保存指针:

int pnt = 7; // global variable - doesn't get deallocated
int* test() {
    int* p = &pnt;
    return p; // this is fine. p is deallocated but we don't need p any more anyway
}

void test2() {
    int* p = test();
    cout << *p; // still fine, it prints 7
}

【讨论】:

  • 为什么你的第二个代码块 [int*p=test(5)] 中有一个 5?它不应该在那里,因为 test() 在你的第二个代码块中没有任何参数?我试图更好地理解指针和内存分配。这个答案有帮助。我只是对 5 感到困惑。
猜你喜欢
  • 2018-09-30
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
相关资源
最近更新 更多