开发者

what's the difference between object * x and object& x in c++ [duplicate]

This question already has answers here: 开发者_StackOverflow中文版 Closed 11 years ago.

Possible Duplicate:

Difference between pointer variable and reference variable in C++

suppose I'm trying to pass a reference to object x to a c++ function...

what's the difference between

pass(Object * x){


}

and

pass(Object& x){

}

and how would you access the actual object itself when the pointer/reference is declared using the different methods...

for instance if I have Object * x, how would I actually access the actual object that is referenced by x

same with Object& x


The first is a pass by pointer. The second is a pass by reference.

As for usage, a pointer must be "dereferenced" before it can be used. That is done with the * and -> operators:

void do_something(Object * x)
{
    Object & ref = *x; // * returns a reference
    ref.method();
    x->method(); // same as (*x).method()
}

References have no such restriction:

void do_something(Object & x)
{
    x.method();
}

However, references can only point to a single object for their whole lifetime, while pointers can change target and (as John mentionned below) point to "nothing" (that is, NULL, 0 or, in C++0x, nullptr). There is no such thing as a NULL reference in C++.

Since references are easier to use and less error-prone, prefer them unless you know what you're doing (pointers are a pretty tough subject).


Pass by reference means the caller should guarantee that the referred object is valid. Pass by pointer usually requires the function to check whether the pointer is NULL.

Pass by reference also means the function don't care about the lifecycle of the object. Pass by pointer may require the function to destruct the object.

So, apparently, pass by reference has clear semantics, less possibility, less error-prone.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜