简体   繁体   English

如何中断此std :: shared_ptr参考周期?

[英]How can I break this std::shared_ptr reference cycle?

Normally, I would break a cycle of shared_ptr s with weak_ptr . 通常,我会用weak_ptr中断shared_ptr的周期。 But I can't see how to do that in this example: 但在此示例中,我看不到该怎么做:

struct A;
struct B;
struct C;
struct D;

struct Cache {
    std::shared_ptr<A> a;
    std::shared_ptr<B> b;
    std::shared_ptr<C> c;
    std::shared_ptr<D> d;
};

struct A {
};

struct B {
    // Same 'a' as in the Cache
    std::shared_ptr<A> a;
};

struct C {
    // Holds a backreference to the cache
    std::shared_ptr<Cache> cache;
};

struct D {
    // Same 'c' as in the cache
    std::shared_ptr<C> c;
};

There are never any cycles between the A , B , etc. The only cycles are backreferences to the Cache . AB等之间从来没有任何循环。唯一的循环是对Cache反向引用。 The Cache needs to stay alive as long as anybody (except the Cache itself) has a shared_ptr<C> , so just using weak_ptr<Cache> won't work. Cache需要保持活着,只要任何人(除了Cache本身)具有shared_ptr<C>所以只用weak_ptr<Cache>将无法正常工作。 For example: 例如:

std::shared_ptr<Cache> make_cache() {
    auto cache = std::make_shared<Cache>();
    cache->a = std::make_shared<A>();
    cache->b = std::make_shared<B>();
    cache->b->a = cache->a;
    cache->c = std::make_shared<C>();
    cache->c->cache = cache;
    cache->d = std::make_shared<D>();
    cache->d->c = cache->c;
    return cache;
}

void use_cache() {
    auto a = make_cache()->a;
    // No need to keep the Cache around

    auto b = make_cache()->b;
    // b->a must be valid

    auto c = make_cache()->c;
    // c->cache must be valid

    auto d = make_cache()->d;
    // d->c (and therefore d->c->cache, etc.) must be valid
}

I understand that in general this would require a garbage collector, but I'm hoping in this specific case there's some trickery that can be done with shared_ptr 's aliasing constructor (8) or something. 我知道通常这需要一个垃圾收集器,但是我希望在这种特定情况下,可以使用shared_ptr别名构造函数 (8)或其他方法来完成一些技巧。

"The Cache needs to stay alive as long as anybody (except the Cache itself) has a shared_ptr<C> ." “只要任何人(缓存本身除外)都具有shared_ptr<C> ,缓存就必须保持活动状态。”

This argues that C controls the ultimate lifetime of the entire structure. 这表明C控制着整个结构的最终寿命。 Therefore, shouldn't the cache be composed into C? 因此,缓存不应该组成C吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM