[英]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
.应该使
actorListPtr
的内容等于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
. std::make_shared<Actor>()
创建一个新的Actor
,但你可能想要this
。 In any case, you can't create an owning shared_ptr
to an arbitrary, pre-existing object which already has an owner.在任何情况下,您都不能为已经拥有所有者的任意、预先存在的对象创建拥有者
shared_ptr
。 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.您似乎正在研究高级 C++ 主题。 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.