简体   繁体   English

我如何安全地分享班级成员?

[英]How do I share class members, safely?

I'm struggling to organise a program. 我正在努力组织一个项目。 I have a class Solver , which looks like this: 我有一个类Solver ,看起来像这样:

class Solver {
   ...
   VarOrder order;
   ...
   vector<Constraint> watches;
   vector<Constraint> undos;
   ...
};

Where of course Solver uses these members to its business. Solver当然Solver这些成员用于其业务。 However, VarOrder also needs to use watches and undoes to do its business and both classes need to be able to see each other's modifications. 但是, VarOrder还需要使用watchesundoes开展业务,两个类都需要能够看到彼此的修改。 So it seems like I need to pass a pointer to the watches and undoes member variables into the constructor of VarOrder . 所以好像我需要一个指针传递给watchesundoes成员变量进入的构造VarOrder I guess I should do that with shared_ptr to be safe, but pointers to vectors seems like opening a massive can of awful. 我想我应该用shared_ptr做到这一点是安全的,但指向向量的指针似乎打开了一大堆可怕的东西。

I could also use the "friends" feature of C++, but that seems wrong as well, since VarOrder only requires access to two of Solver 's members, not all of them, which seems like it would be weird design. 我也可以使用C ++的“朋友”功能,但这似乎也是错误的,因为VarOrder只需要访问Solver的两个成员,而不是所有成员,这似乎是奇怪的设计。

Probably my class design is wrong, but short of creating global data, I don't know how to reorganize this. 可能我的班级设计错了,但没有创建全局数据,我不知道如何重组这个。 Any advice appreciated. 任何建议表示赞赏

Thank you. 谢谢。

No need to use shared pointers in this case, as those vectors have been allocated on the stack along with VarOrder and so they will all exist for the lifetime of each other. 在这种情况下不需要使用共享指针,因为这些向量已经与VarOrder一起分配在堆栈上,因此它们将在彼此的生命周期中存在。 Have VarOrder take a reference to the others (so no null pointer issues). VarOrder 引用其他内容(因此没有空指针问题)。

class VarOrder {
private:
    vector<Constraint>& _watches;
    vector<Constraint>& _undos;

public:
    VarOrder(vector<Constraint>& watches,
             vector<Constraint>& undos) : _watches(watches)
                                        , _undos(undos) {
    }; // eo ctor
}; // eo class VarOrder

class Solver {
private:
    vector<Constraint> _watches;
    vector<Constraint> _undos;
    VarOrder _order;

public:
    Solver() : _undos()
             , _watches()
             , _order(_watches, _undos) {
    }; // eo ctor
}; // eo class Solver

Note that members are initialised in the initialiser-list in the order in which they are declared in the class , so by the time _order comes around to construction, _undos and _watches are fully constructed. 请注意,成员在初始化列表中按照在声明的顺序进行初始化,因此,当_order进入构造时, _undos_watches是完全构造的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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