开发者

I am a little confused about memory pointers

I have been teaching myself C++ in the last few days, and have run into some situations that I could use some further explanation on. What is the difference between the following methods besides the obvious class, naming, etc?

void OnTimer(wxTimerEvent &event) ...

void addNPC(Sprite *spr) ...

Are both those methods receiving values passed by reference and doing the same thing? If so, what is the difference? When I first started reading, I saw the method called like this:

addNPC( &sprite );

So I assumed that when you wrote a method that would be receiving a memory pointer, in the method arguments you must write it like you were decla开发者_运维问答ring a memory pointer/location, and not just a value. But then I look at the OnTimer method, and I see that it also has a reference being passed. What's the difference?

Finally, are these two things the same, and just actual coding styles?

void addNPC(Sprite& spr) ...
void addNPC(Sprite &spr) ...


Last question first: the two function prototypes are equivalent. Whitespace is mostly not significant in C or C++.

As for the difference between references and pointers, think of a reference as "syntactic sugar" for a pointer, with the additional restriction that it cannot be NULL. For more on this, see the C++ FAQ: https://isocpp.org/wiki/faq/references


void addNPC(Sprite *spr)

In above code, you need to pass address of Sprite object like below, as it receives pointer.

addNPC( &sprite );  

And for the function

void OnTimer(wxTimerEvent &event) 

call has to be like below as it takes reference to wxTimerEvent object.

wxTimerEvent evt;
OnTimer(evt);//Passing object by reference.

At calling place, Syntax is same for both pass by value and pass by reference.

And for your last question, they both are same, just the coding style difference.


wxTimerEvent &event is a reference to an object. It acts like and looks like a normal variable but it references a variable outside of the function. Any changes made to the local references are actually changing the original. It is essentially a pointer that you can access as a normal variable and it cannot be NULL.

Sprite *spr is a real pointer to an outside variable. Any changes made to it locally are also made outside the function. It can be NULL!

The last two items are identical. Spaces are not significant in C/C++ code.


In addition to other answers there is one feature of const reference - you can assign temporary object to it and object will live as long as const reference is alive.

string its_alive();

void foo() {
  const string& some_string = its_alive();
  ...
}

So you use references if the user of the reference not responsible for object's destruction AND if NULL object makes no sense.

Here's honorary GotW #88 for explanation of const reference to temporary object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜