Search code examples
c++shared-ptr

C++ Pointer does not behave as expected


Say I have a class similar to this.

class Actor {
public:
    add()
    {
        auto tmp = std::make_shared<actor>();
        actorListPtr.push_back(tmp);
    }

    static std::vector<shared_ptr<Actor>> & actorListPtr;
}

What I wish by this is to have a link to a separate vector, a vector with the same behavior for each individual instance of the class, referenced from another source. Any changes made in the source are to be reflected upon its pointer and vice versa. For instance.

std::vector<shared_ptr<Actor>> actorList;
Actor::actorListPtr = actorList;

Actor guy;
guy.add();

Should make the contents of actorListPtr equal to actorList. However, for me, this is not the case. What am I missing?


Solution

  • What I wish by this is to have a link to a separate vector, a vector with the same behavior for each individual instance of the class, referenced from another source. Any changes made in the source are to be reflected upon its pointer and vice versa.

    You seem to be treading on advanced C++ topics. There's a design pattern for this. It's called Dependency Injection.

    Here's one way to make it work.

    class Actor {
       public:
          void add()
          {
             auto tmp = std::make_shared<Actor>();
             if ( actorListPtr )
             {
                actorListPtr->push_back(tmp);
             }
          }
    
          // Allow client code to inject a pointer to be used on subsequent
          // calls to add().
          static void setActorList(std::vector<std::shared_ptr<Actor>>* newActorListPtr)
          {
             actorListPtr = newActorListPtr;
          }
    
       private:
          static std::vector<std::shared_ptr<Actor>>* actorListPtr;
    }
    
    // The static member variable is initialized to nullptr.
    // Client code sets the value.
    std::vector<std::shared_ptr<Actor>>* Actor::actorListPtr = nullptr;
    

    // Client code.
    
    std::vector<shared_ptr<Actor>> actorList;
    Actor::setActorList(&actorList);
    
    Actor guy;
    guy.add();