C++ 指针的行为不符合预期

C++ Pointer does not behave as expected

假设我有一个与此类似的 class。

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

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

我希望的是有一个 link 到一个单独的向量,一个向量对 class 的每个单独实例具有相同的行为,从另一个来源引用。在源中所做的任何更改都将反映在其指针上,反之亦然。例如.

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

Actor guy;
guy.add();

应该使actorListPtr的内容等于actorList。然而,对我来说,情况并非如此。我错过了什么?

std::make_shared<Actor>() 生成一个新的 Actor,但您可能需要 this。在任何情况下,您都不能为已经拥有所有者的任意 pre-existing 对象创建拥有 shared_ptr。改为尝试:

class Actor {
public:
    static Actor & make()
    {
        auto tmp = std::make_shared<Actor>();
        actorListPtr.push_back(tmp);
        return * tmp;
    }

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

Actor & guy = Actor::make();

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.

您似乎在讨论高级 C++ 主题。有一个设计模式。它被称为 Dependency Injection

这是让它发挥作用的一种方法。

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();