指针-以C ++返回本地引用 [英] Pointer - returning Local reference in C++

查看:90
本文介绍了指针-以C ++返回本地引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定是否曾经问过这个问题(通过SOF搜索并找不到答案)

I'm not sure if this question has been asked before ( searched through SOF and couldn't find an answer)

我编写了一个LinkedList类和一个将其反向的函数.该函数如下,

I wrote a LinkedList class and a function to reverse it.The function as follows,

    struct LinkedList::element* LinkedList::recurrsiveReverseList(element* head){
     element* tempList;
     if(head->next == NULL){
        return head;
     }else{
        tempList = recurrsiveReverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return tempList;        
    }
   }

在这里,我声明一个局部指针变量,并对它进行一些更改,然后将其返回给调用者.在C ++中,当我在函数内部声明局部变量时,作用域仅存在于函数内部.现在,当我从函数返回指针时,它是如何工作的?我能够理解逻辑并得到结果(幸运的是),但我无法完全理解此处的工作.

here I am declaring a local pointer variable and making some changes to it and returning it back to the caller. In C++, when I declare a local variable inside a function the scope exists only inside the function. Now when I return the pointer from the function how does it work? I am able to understand the logic and get the result (luckily) but I am not able to completely understand the working here.

有人可以消除我的疑问吗?

Can somebody clear my doubt?

推荐答案

当您退出函数时,tempList的作用域终止,但是tempList是指向其作用域不是的内存块的指针终止于此,因为它无疑是由new分配的.这样分配的内存一直有效,直到您delete为止,无论您要进入或退出多少功能.

The scope of tempList terminates when you exit the function but tempList is a pointer to a block of memory whose scope does not terminate there because it's been undoubtedly allocated by new. Memory allocated in such a way is valid right up until the point you delete it, regardless of how many functions you go in to or out of.

通过将指针传递回调用方,它会将所述指针保留在其他地方,供您使用.

By passing the pointer back to the caller, it preserves said pointer elsewhere, where you can use it.

一个简单的例子:

static char *fn (void) {
    char *rv = new char[42];
    return rv;
}

int main (void) {
    char *x = fn();
    delete [] x;
    return 0;
}

在上面的代码中,rv的范围在声明后限制为fn函数.

In the code above, the scope of rv is limited to the fn function after it's declared.

x的范围在声明后限制为main函数.

The scope of x is limited to the main function after it's declared.

但是,由new分配的内存在fn中存在,并且继续在返回main之后仍然存在.最初存储在rv中的所述内存的地址通过将fn返回值分配给x而传输到x.

However the memory allocated by new comes into existence within fn and continues to exist after returning to main. The address of said memory, initially stored in rv, is transferred to x by the assignment of the fn return value to x.

这篇关于指针-以C ++返回本地引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆