0

So I was looking at the source code of unreal engine and I came across this:

class USphereComponent* CollectionSphere;

There are using pointer for something that is going to be initialized and spawned once when the game begins and some objects will be overlapping it,I thought pointers are mainly used for more mid-high memory allocation purposes So why are they using it now?

Keep in mind Im not really good at pointers so Im just trying learn and gather some information about it.

  • 3
    Impossible to fully answer without more context. You can allocate pointers anywhere. Just exercise care and use containers or smart pointers where possible. – user4581301 Dec 30 '16 at 18:58
  • what do you need to know more? – Doğukan Özdemir Dec 30 '16 at 19:07
  • Bit late coming back to the ball. Sorry about that. By more context I'd need to see how the programmer used `CollectionSphere`. Lightness Races in Orbit is probably correct, but another possibility is the programmer likely didn't have enough information (how many, which polymporphic instance, what constructor parameters, etc...) to initialize the object. By seeing how the object is initialized and used, we can eliminate some of the chaff. But at the end of the day we're just guessing at the programmer's intent. For all we know, using a pointer could be a mistake. – user4581301 Dec 30 '16 at 20:38

1 Answers1

3

Whether to use pointers or not has almost nothing to do with "low" or "mid-high memory allocation purposes".

You use a pointer when you need a pointer, and often that's when the pointee (the thing being pointed to) will live for longer than an "automatic" object would in any of the program's existing, conveniently-accessible scopes.

Basically, *CollectionSphere will be a global (or something similar), but we can't construct it right away. The author has decided that they need fine control over the lifetime of the object. So, they have created a pointer to point to that object when the time comes.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055