0

I'm trying to design a class to design a 3D mesh in C++. My idea is the following: 3 base classes: Point, Polygon, Polyhedron (the mesh has to handle very general shapes) The class Polygon contains a vector of shared pointers to Point (the vertexes), in the same way, Polyhedron contains 2 vectors of shared pointers to Point and Polygon. It would be very useful to have inside Polygon a vector of shared pointers to Polyhedron and inside Point 2 vector of shared pointer of Polyhedron. In this way, every Point would know the polygons and polyhedrons connected to it.

I have already implemented the classes (using enable_shared_from_this) in this way and all works quite well, but now I have some doubts about this. Is this design a good design or it may lead to some problems? Is a bad behavior to have 2 objects connected by shared pointers? How is the memory management in this case?

The shared pointers are very important in the connection Polygon->Point, Polyhedron->Point and Polyhedron->Polygon, but not so necessary in the other direction. I thought that I may use a weak pointer instead of shared ones, in this way Point would not be responsible for Polygon and Polyhedron life. I prefer not to use standard pointers.

I would like to know your opinion, thank you very much!

hackjutsu
  • 8,336
  • 13
  • 47
  • 87
stefano1
  • 161
  • 10

2 Answers2

1

The std::shared_ptr graph must not contain cycles, otherwise you've got a memory leak as each object keeps the next one alive.

Break the cycles with std::weak_ptrs.

Quentin
  • 62,093
  • 7
  • 131
  • 191
1

Having shared pointer in both directions means your memory won't be freed. You should use shared pointers in the ownership direction (the ones that you say are important) and weak pointers the other way.

All it takes is assigning the shared pointers to weak pointers when storing them and making sure to check expiry before using the weak pointer.

FrankM
  • 772
  • 7
  • 11