简体   繁体   English

C++中指针引用的生命周期

[英]The lifetime of a pointer reference in C++

I wrote some code that involves moving and changing variables in C++.我写了一些涉及在 C++ 中移动和更改变量的代码。 Below is what I have wrote.下面是我写的。

#include <iostream>

void six(int*& ptr) {
    int s = 6;
    ptr = &s;
}

int main() {
    int f = 5;
    int* ptr = &f;

    std::cout << *ptr << '\n';
    six(ptr);

    if (ptr) {
        std::cout << *ptr;
    }
    else {
        std::cout << "null\n";
    }

    return 0;
}

so this prints:所以这会打印:

5
6

I tried another code, adding a single line:我尝试了另一个代码,添加了一行:

#include <iostream>

void six(int*& ptr) {
    int s = 6;
    ptr = &s;
    free(&s); // added line
}

int main() {
    int f = 5;
    int* ptr = &f;

    std::cout << *ptr << '\n';
    six(ptr);

    if (ptr) {
        std::cout << *ptr;
    }
    else {
        std::cout << "null\n";
    }

    return 0;
}

Obviously, this gives an error after printing 5 because what the modified pointer is pointing is not available when called the second time.显然,这在打印5后会出错,因为第二次调用时修改后的指针指向的内容不可用。

However, I am confused at the first case.但是,我对第一种情况感到困惑。 When calling six in the main function, variable s is not in the main scope, but the value itself still continues to remain in the memory to be referenced.在 main 函数中调用six时,变量s不在 main 作用域内,但值本身仍然继续留在内存中被引用。 Doesn't C++ automatically destroy variables and clean them when it goes out of the scope?当变量超出范围时,C++ 不会自动销毁变量并清除它们吗? Is this a memory leak?这是内存泄漏吗?

The first case is not a memory leak, but an undefined behaviour because your variable go out of scope.第一种情况不是内存泄漏,而是未定义的行为,因为您的变量超出了范围。

In this case you don't know when the memory will be cleaned(replaced) o reallocated.在这种情况下,您不知道何时清理(替换)或重新分配内存。

So in some case the result can be correct but it's a pure question of luck.因此,在某些情况下,结果可能是正确的,但这纯粹是运气问题。

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

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