I just started learning C++.
In C I would just use Node* cur_node, but in C++ this doesn't work:
struct Node { int val; }; struct Foo { unique_ptr<vector<Node>> nodes; unique_ptr<&Node> cur_node; }; int main() { Foo foo; foo.nodes = make_unique<vector<Node>>(); foo.nodes->push_back((Node){.val=100}); //d.cur_node = d.nodes[0]; foo.cur_node = make_unique<&Node>(((*d.nodes)[0])); (*d.nodes)[0].val = 200; cout << d.cur_node->val << endl;; cout << (*d.nodes)[0].val << endl;; } error: 'Node' does not refer to a value unique_ptr<&Node> cur_node; If I don't use a reference, the value is copied, and I can't modify the original vector by modifying cur_node.
Maybe I need shared_ptr for this?
edit
To make it more clear: I want cur_node to contain a reference to one of the values in the vector, and to modify the original vector by modifying cur_node, just like I would with raw C pointers.
Thanks
unique_ptr<vector<Node>> nodes;? Won'tvector<Node> nodes;be enough?cur_nodeshould always point to either none element or one of the nodes stored innodes, but never to any other node?protectedand the access/manipulation should be controlled by member function, otherwise this cannot be ensured. And if the access/manipulation is controlled by member function then you could useNode *forcur_nodeyou anyhow need to do something like that because references or pointers to the elements innodescan/will become invalid when you add new elements to that vector.