12 ms·
An example: `std::shared_ptr<sf::RenderWindow> window;` - your main window really doesn't need multiple owners - it can be singly owned by `main()` or whatever
by a_t48 4y ago
An example: `std::shared_ptr<sf::RenderWindow> window;` - your main window really doesn't need multiple owners - it can be singly owned by `main()` or whatever the top level construct is for your game with `std::unique_ptr`. If you need to pass the window to some other function, do it by raw pointer or ref, signaling that "here's this object for you to use, but not own". `shared_ptr` should only be used for pointers that actually have multiple owners. The textures here might be a good example for this - you could implement a simple resource system that drops unused resources with `shared_ptr` + `weak_ptr`.
As for why - it's mostly around signaling intent and protecting against leaks. It's much easier to reason about ownership if you don't have to worry about some object deep inside your engine hierarchy holding a `shared_ptr` to the object that owns it. This can still happen with unique_ptr, but is much less likely.
- snakey 4y agoGreat explanation, as someone who is new to C++ and actively learning, these perspectives are invaluable. I have been using some shared pointers in a personal project because of its ease of use but I aim to review and refactor this code to follow C++ idioms more appropriately. Thank you!
- typon 4y agoIn these cases I usually opt for gsl::not_null<T>
- SuperV1234 4y agoYou don't even need 'unique_ptr'. The render window on its own is completely fine.
- a_t48 4y agoIn this somewhat toy case - yes. :)