我怎样才能打破这个标准::shared_ptr参考循环
How can I break this std::shared_ptr reference cycle?
通常,我会用weak_ptr
打破shared_ptr
s的循环。 但是在这个例子中我看不到如何做到这一点:
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;
};
A
、B
等之间从来没有任何循环。 唯一的循环是对Cache
的反向引用。 只要任何人(除了Cache
本身)有shared_ptr<C>
,Cache
就需要保持生命,所以仅仅使用weak_ptr<Cache>
是行不通的。 例如:
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
}
我知道一般来说这需要一个垃圾收集器,但我希望在这种特定情况下,可以使用shared_ptr
的别名构造函数 (8) 或其他东西来完成一些技巧。
"只要任何人(缓存本身除外)有
shared_ptr<C>
,缓存就需要保持活动状态。"
这认为C控制了整个结构的最终寿命。因此,缓存不应该组合成 C 吗?
相关文章:
- 使用CMake检测支持的C++标准
- 如何理解C++标准N3337中的expr.const.cast子句8
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 编译标准库类型
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 铸造标准::有没有回到原来的类型
- 标准 N3337 5.2.10 第 7 条中的C++"类型"是什么意思?
- this_thread::sleep_for和计时时钟之间的关系是否由C++11标准指定
- 标准库类型的赋值运算符的引用限定符
- 标准是否严格定义了该程序应该如何编译?
- 如何从Windows应用程序输出到标准?
- 安全到标准:移动会员?
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 这是否符合C++标准:双响双响,例如!!(-0.0).
- 标准::变体的赋值运算符
- 捕获标准输出以压缩并使用 CTRL-C 中断会给出损坏的 zip 文件
- 如何在 Mac 上使用 c++17 并行标准库算法?
- 强枚举类型定义:Clang Bug 还是 C++11 标准不确定性?
- 并行标准::复制复杂性