Reputation: 13145
I am working with a lot of interfaces for the purposes of dependency injection (test driven development.) For this reason a lot of my objects are pointed to via std::shared_ptr. I would have used std::unique_ptr but they dont have a copy constructor as required when google mocking.
What measures can I put in place with a view to early detection of circular references if they were to occur?
I'm working on the linux platform with google test.
Upvotes: 3
Views: 3085
Reputation: 4291
It's impossible to detect circular references with shared pointers automatically, one technique which I use to detect circular references is to do it explicitly in the following manner. Maintain a globally accessible std::vector< T* >
, in all the ctors add the object to the vector, and then in the dtors remove it. Then in the end of main you just check to see that the vector is empty, if it isn't then you likely have a circular references somewhere, and the vector will help you track down where. If you have shared pointers owned by statically allocated objects it's easy to run into false positives, especially as static initialization order fiasco applies.
In boost there's the define BOOST_SP_ENABLE_DEBUG_HOOKS
through which it's possible to do this application wide for all types.
Upvotes: 7
Reputation: 67782
If you have a graph of homogenous objects (ie, Node -> Node -> Node ...
), you can use the usual cycle-detection algorithms.
If your graph is heterogenous (Document -> Element -> Table -> Document
or whatever), traversing it might be just too painful ... although perhaps feasible with a clever custom iterator type.
In that case, it's more usual to structure your ownership semantics so there can be no cycle, perhaps using weak_ptr
to break statically-identifiable cycles.
Upvotes: 1