SFML community forums
Help => General => Topic started by: codelyoko373 on August 22, 2017, 04:35:35 am
-
(Sorry if this is in the wrong place)
I firstly want to point out I know what pointers are and how to use them though they're still quite a confusing topic to me. I can see how they're useful when you're for example wanting to pass a variable around through functions without making copies of it but that's about it.
Should I be making all variables pointers or not for example?
(https://image.prntscr.com/image/fn45tPNiTGiUhltunFp__A.png)
The reason I mainly ask this is because the tutorial series I watched for making pong in sfml, the guy basically always created pointers, all his variables were pointers so I've done exactly the same thing but it doesn't feel right.
-
Firstly, a bit of theory:
https://stackoverflow.com/a/79936
Now, If the stack model is convenient for you (small size, short lifespan, etc..), use it, there's no reason not to (however,make sure you're not creating global variables just so you can use stack model. Always avoid globals). Only use heap if stack memory management is insufficient.
On top of that, when you finally use pointers, use smart pointers (https://github.com/9lean/CplusPlus_SmartPointer) instead of the raw ones, as smarts are safer.
-
Raw pointers should in pretty much all cases be avoided.
If you want to pass a variable without making a copy, use a reference.
If you want to dynamically allocate an object, use a smart pointer (i.e. std::unique_ptr).
-
Firstly, a bit of theory:
https://stackoverflow.com/a/79936
Now, If the stack model is convenient for you (small size, short lifespan, etc..), use it, there's no reason not to (however,make sure you're not creating global variables just so you can use stack model. Always avoid globals). Only use heap if stack memory management is insufficient.
On top of that, when you finally use pointers, use smart pointers (https://github.com/9lean/CplusPlus_SmartPointer) instead of the raw ones, as smarts are safer.
So I'm guessing I shouldn't be making all those pointers then? (Shown in the screenshot)
-
So I'm guessing I shouldn't be making all those pointers then? (Shown in the screenshot)
No. This should not be your default way of storing objects. For a lot of projects, you can just create the objects directly on the stack (sf::Text title;) but for larger projects with an extreme amount of objects and large objects that you do need on the heap (e.g. resources), use smart pointers to store them (std::unique_ptr<sf::Font> font;).