简体   繁体   中英

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. The value itself is a copy, meaning that if you do 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

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

@CIsForCookies Nicely explained...

Adding a small detail:

[...] or a copy of that pointer and hence every pointer should be assigned to null when not needed anymore?

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...

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). 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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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