简体   繁体   中英

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?

std::make_shared<Actor>() makes a new Actor , but you probably want this . In any case, you can't create an owning shared_ptr to an arbitrary, pre-existing object which already has an owner. Try instead:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM