简体   繁体   English

在C ++中传递/检索指针

[英]Passing/Retrieving pointers in C++

在C ++中通过指针传递或检索对象时,已知对象本身不会被复制,但是指针如何处理,接收函数也会处理该对象的相同指针或该指针的副本,从而处理每个指针当不再需要时,应将其分配为null。

When passing a pointer in c++ (ie foo(some_object* p) ) you actually pass the value of the pointer, where the object resides. 当在c ++中传递指针时(即foo(some_object* p) ),您实际上传递的是对象所在的指针的值。 The value itself is a copy, meaning that if you do p = NULL; 该值本身是一个副本,这意味着如果您执行p = NULL; inside your function, that won't change the original pointer, but the address it points to holds the same original object. 在函数内部,它不会更改原始指针,但是它指向的地址包含相同的原始对象。

Example: 例:

#include <iostream>
using namespace std;

class obj{
public:
  int a;
};

void foo(obj* pp){
    pp->a = 2;
    pp = NULL;
    cout << pp << endl;
}
int main() {
    obj* p = new obj();
    p->a = 1;
    cout << p << '\t' << p->a << endl;
    foo(p);
    cout << p << '\t' << p->a;
    return 0;
}

You'll note that the p stays the same after foo is executed although it was changed inside, since what was change was a copy of p while a was actually changed during foo 您会注意到,尽管在内部执行了更改,但p在执行foo之后仍保持不变,因为更改的是p的副本,而afoo期间实际上已更改

指针已被复制,但是由于该副本的值仍位于相同的内存位置,因此您仍然可以修改副本所指向的变量。

@CIsForCookies Nicely explained... @CIsForCookies很好地解释了...

Adding a small detail: 添加一个小细节:

[...] or a copy of that pointer and hence every pointer should be assigned to null when not needed anymore? [...]或该指针的副本,因此在不再需要时应将每个指针分配为null吗?

Function parameters are variables local to the function, just as variables declared inside the function body. 函数参数是函数本地的变量,就像在函数体内声明的变量一样。 This means that their life time ends as soon as the function returns. 这意味着一旦函数返回,它们的生命周期就会结束。

So setting any pointers to null right before returning is in vain as afterwards, the (copied) pointer simply won't exist any more... 因此,在返回之前将任何指针设置为null都是徒劳的,因为之后,(复制的)指针根本不再存在了...

The pointer is just a number (like int variable), that points to a memory cell where the variable is stored (to the beginning of it actually). 指针只是一个数字(如int变量),它指向存储该变量的存储单元(实际上指向它的开头)。 If you pass int variable into a function, you don't have to set it to 0 after usage, the compiler will do it for you. 如果将int变量传递给函数,则在使用后不必将其设置为0 ,编译器将为您完成此操作。

Also if you pass a variable without a reference, it's most likely that a temporary copy will be used. 同样,如果您传递的变量没有引用,则很有可能会使用一个临时副本。

void test (VarType* ptr) {...}

You could use a const reference to a pointer, it would behave like a const reference to a variable: 您可以使用对指针的const引用,其行为类似于对变量的const引用:

void test (VarType* const& ptr) {...}

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

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