Reputation: 1153
I'm struggling to organise a program. I have a class Solver
, which looks like this:
class Solver {
...
VarOrder order;
...
vector<Constraint> watches;
vector<Constraint> undos;
...
};
Where of course Solver
uses these members to its business. 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. So it seems like I need to pass a pointer to the watches
and undoes
member variables into the constructor of 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.
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.
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.
Upvotes: 0
Views: 81
Reputation: 38825
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. Have VarOrder
take a reference to the others (so no null pointer issues).
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.
Upvotes: 2