Is it bad practice to implement a graph's nodes as a vector of pointers?

时间:2015-10-30 23:50:49

标签: c++ pointers vector

I am attempting to implement a graph in C++ where each node is an instance of class A. My first instinct was to represent the collection of nodes in a Graph object by a vector of objects of type A. However, I wanted to implement the following functionality as well: Suppose I overload the + operator so that when g_2 = g_0 + g_1 (where the g's are instances of the Graph class), g_2's nodes consist of the combined nodes of g_0 and g_1. If I modify any of the nodes in g_2, g_0 and g_1's nodes will remain unchanged and in a certain sense g_2 will no longer remain the sum of g_0 and g_1. However, if I instead represent the nodes in a graph as a vector of pointers to objects of type A, then modifying g_2 will modify g_0 and g_1, and vice versa, which would be desirable for the project I am working on. That being said, I can't help but suspect that having a vector of pointers as a data member is dangerous, but I don't know enough to really say.

2 个答案:

答案 0 :(得分:1)

A vector of pointers is fine. You just need to take care of the memory management of your objects yourself, but this is definitely doable. You will need to allocate your objects with new A() and delete them with delete pointer_to_a if you want to get rid of them.

答案 1 :(得分:1)

Having vector of pointers is fine. I think is a common practice. It won't be hard or dangerous if you use smart pointers like shared_ptr. typedef std::shared_ptr<A> A_ptr; std::vector<A_ptr> nodes; It will take care of memory managment.
相关问题