So, I've found myself doing this a lot, and wonder if it's correct practice (this probably won't compile - I'm writing this on my phone):
class Shared { private: int _x; public: void X(int newValue) { _x = newValue; } int X() { return _x; } Shared(void) : _x(0) { } }; class Owner { private: shared_ptr<Shared> _shared; public: const Shared& Shared() const { return *_shared; } void Shared(const Shared& newValue) { _shared.reset(&newValue); } void DoSomethingWithShared() { /// yeah, this could be cleaner, not the point! _shared.X(_shared.X() + 1); } }; void CreateStuff(Owner& a, Owner &b) { Shared s; a.Shared(s); b.Shared(s); } int main(int argc, char *argv[]) { Owner a; Owner b; CreateStuff(a,b); a.DoSomethingWithShared(); b.DoSomethingWithShared(); ///... /// "Shared" instance created in CreateStuff() hopefully lives until here... } The idea is that multiple instances of Owner need a shared resource of type Shared.
Is
CreateStuff()an error? (ie, doessgo out of scope, leavingaandbwith invalid pointers to a destroyed object? (Am I returning the address of a temporary in a roundabout way?)Are there any other scope/GC issues I'm not seeing?
Is there an easier way to do this?