3

为了依赖注入(测试驱动开发)的目的,我正在使用很多接口。因此,我的很多对象都通过 std::shared_ptr 指向。我会使用 std::unique_ptr 但他们在谷歌模拟时没有所需的复制构造函数。

如果发生循环引用,我可以采取哪些措施以及早发现循环引用?

我正在使用谷歌测试在 linux 平台上工作。

4

2 回答 2

7

使用共享指针自动检测循环引用是不可能的,我用来检测循环引用的一种技术是通过以下方式显式执行此操作。维护一个全局可访问的std::vector< T* >,在所有 ctors 中将对象添加到向量中,然后在 dtors 中将其删除。然后在 main 结束时,您只需检查向量是否为空,如果不是,那么您可能在某处有循环引用,并且向量将帮助您找到位置。如果您拥有由静态分配的对象拥有的共享指针,则很容易遇到误报,尤其是在应用静态初始化顺序惨败时。

在 boost 中,有一个定义BOOST_SP_ENABLE_DEBUG_HOOKS,通过它可以在所有类型的应用程序范围内执行此操作。

于 2012-07-12T10:13:27.233 回答
1

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.

于 2012-07-12T10:05:55.570 回答