pointers - c++ push_back copying object instead of reference -
i'm having issues understanding problem i've mentioned in comments below:
class node { public: node(int value): value(value), neighbors() {} int value; std::vector<std::shared_ptr<node>> neighbors; }; std::vector<node> nodes; nodes.reserve(50); for(int j = 0 ; j < 50; ++j) { nodes.push_back(node(j)); } for(int j = 1 ; j < 25; ++j) { nodes.at(0).neighbors.push_back(std::make_shared<node>(nodes.at(j))); } //the following line copying nodes.at(0) instead of //copying reference nodes.at(0). why? nodes.at(15).neighbors.push_back(std::make_shared<node>(nodes.at(0))); for(int j = 25 ; j < 50; ++j) { nodes.at(0).neighbors.push_back(std::make_shared<node>(nodes.at(j))); } std::cout << nodes.at(15).neighbors.at(0).neighbors.size(); //prints out 24 std::cout << nodes.at(0).neighbors.size(); //prints out 49
why following line copying nodes.at(0) (which returns reference first element of nodes vector) instead of storing reference it?
nodes.at(15).neighbors.push_back(std::make_shared<node>(nodes.at(0)));
nothing in code stores references. code copies node because allocate new node in std::make_shared
, invoke copy constructor.
std::vector<node> nodes;
it's local function. impossible keep either pointers (shared or not) or references elements of vector. perhaps want use vector of shared pointers instead:
std::vector<std::shared_ptr<node>> nodes;
bear in mind shared_ptr doesn't work in presence of cyclic referenced. if data structure general graph, perhaps shared_ptr not appropriate storing neighbours. may want consider weak_ptr instead (you have keep container of shared pointers nodes separately).
Comments
Post a Comment