【问题标题】:Does an instance of boost::bind retain a shared_ptr for it's lifetime?boost::bind 的实例是否在其生命周期内保留 shared_ptr?
【发布时间】:2014-04-28 23:46:11
【问题描述】:

boost 绑定是否会在其生命周期内增加 shared_ptr 参数的引用计数?比如下面的代码:

void myFunc(boost::shared_ptr<MyClass> in) {
    in->doThing();
}

void myOtherFunc() {
    {
        boost::shared_ptr<MyClass> p = ...;
        // A
        boost::function<void(boost::shared_ptr<MyClass>)> f = boost::bind(&myFunc, p);
        // B
    }
    // C
}

如果 bind 确实增加了 ref 计数,则 ref 在 A 处应为 1,在 B 处为 2,在 C 处为 0。

【问题讨论】:

标签: boost boost-bind


【解决方案1】:

是的,boost::bind(以及std::bindcreates functor that holds copies 的参数,但不能指望复制的数量。因此,您只能假设在点 (B) 的引用数量大于在点 (A) 的数量。当然,当函子被销毁时,它所持有的所有shared_ptr 都会被释放。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2017-06-18
    • 2019-04-16
    相关资源
    最近更新 更多