I'm having some difficulties trying to solve a pointer problem in C++.
Let's say I have class called MyClass. Inside this class, there is a shared pointer that points at some outside resource called MyResource. Now let's also say that within MyClass, there are a few instances of an object called MyObject. Each instance of MyObject also needs to reference MyResource. Let's assume this class doesn't do anything except contain these components I've just mentioned
class MyClass { shared_ptr<MyResource> m_p_my_resource; MyObject m_my_object1; MyObject m_my_object2; MyObject m_my_object3; } How I had previously (tried to) implemented this, I would create a shared pointer and give it to m_p_my_resource. I would then give m_p_my_resource to each instance of MyObject. I assumed that whenever m_p_my_resource changed to point at a new MyResource, each of MyObjects would also point at the new resource.
However, I realize what I did wasn't correct. When I would change m_p_my_resource, this would indeed be pointing at a new resource. However, each instance of MyObject would still be pointing at the original MyResource.
Now I'm trying to think of methods on how to actually implement what I was originally trying to do: be able to change m_p_my_resource and have each instance also point at the new resource.
One way to solve this is to update each instance of MyObject whenever m_p_my_resource changes. I would likely need to have a setResource method that would update m_p_my_resource and then iterate through each instance of MyObject.
An alternative solution is to have each instance of MyObject contain a pointer to a pointer of MyResource. So if each MyObject was pointing at a pointer to the resource instead of the resource itself, I could change m_p_my_resource and each object would also be able to determine the new resource.
While this second method would probably work in the class example I listed above, it's not elegant for instances of MyObject not contained within a class. As in, if I simply created a MyObject on the stack, I would rather have it point directly at the resource instead of having it point at some intermediate pointer that is pointing to the resource...
So I'm trying to determine the best method for implementing what I describe. I'm still relatively new to smart pointers and am curious if what I'm trying to do is stupid, or if there a better/obvious alternative solution.
MyResourceis immutable).