Two Conceptual Questions: i) (Smart) Pointers vs. References ii) How to return objects from functions?
Hi, I'm in the process of learning C++ and I'm a little confused about two things. Hoping the reddit community can help me out.
i. When to use smart pointers vs references: Is it the general "rule of thumb" to just use references until you can't anymore? Source. Or is it more preferred to pass objects by (smart) pointer?
ii. How to return objects from functions (i.e. created on the stack)? Is passing a return parameter frowned upon? Or, is it better to just return by copy and let the compiler optimize?
Thank you very much!
Posted Jun 22, 2019, 4:32 AM UTC · edited
I'm not super experienced in c++ but these are the guidelines I try to follow.
In this scenario, how does the user of the pointer know that the pointer is still valid (since the pointed to object is owned by something else)?
Exactly. Return a pointer if pointed object will outlive the purpose. Otherwise, things get complicated. Depends on use case.. If you need access to the object after the current holder / owner is done with it, then either smart pointers or refactoring is required.
You can't. Although this would only be a case in legacy systems, but that is a whole other story for "what to/not to do". The only effective solution would be to use sharedptr, if you must really follow such a scenario.
1 and 2 wouldn’t that be unique vs shared pointers? As opposed to smart vs raw.
Raw pointer signals access intent, whereas shared ptr signals (shared) ownership. In general your interface that uses / modifies an object but doesn't buffer it should use raw pointers.