【问题标题】:Destroying an object with ongoing function call使用正在进行的函数调用销毁对象
【发布时间】:2015-11-10 06:41:19
【问题描述】:

假设我有资源 B 的类 A。类 A 有一个函数,在我想销毁它之前没有获取互斥锁。我调用 boost::shared_ptr::reset() 来销毁类 A 的实例。资源 B 是否保证在那时被销毁?

class Resource{
public:
    Resource(){ }
    ~Resource(){ free(); }
    void init() {}
    void free() {}  
};

class A{
public:
    A(){ B.init(); }
    ~A(){}

    void functionC(){
        boost::lock_guard<boost::mutex> lock(Mutex);
        // Stuck forever
        boost::lock_guard<boost::mutex> lock2(Mutex);
    }
private:
    boost::mutex Mutex;
    Resource B;
};

main(){
    boost::shared_ptr<A> pointer(new A());

    // Do a function call that gets stuck but allows main thread to continue
    boost::thread t(boost::bind(&A::functionC, *pointer));

    pointer.reset();

    // Loop forever
    while(1);
}

具体来说,我希望在调用pointer.reset() 时调用函数B::free()。这段代码是否保证可以做到这一点,还是我必须在某处明确调用它?显然我不想这么明确

pointer->freeB();
pointer.reset();

【问题讨论】:

    标签: c++ boost mutex shared-ptr


    【解决方案1】:

    在您的场景中,B 是 A 的成员。当 A 被销毁时,它将被销毁(并且 free() 将被调用)。无需显式调用。

    但是,在您的代码中,不能保证您的 pointer.reset() 分配的 A 对象被销毁:只有当 pointer 是唯一指向该对象的 shared_ptr 时,它才会被销毁,即没有复制指针自创建以来(这里没有证据,但要在您的真实代码中检查)。

    顺便说一句,您的代码中缺少t.join()

    【讨论】:

      猜你喜欢
      • 2014-08-28
      • 1970-01-01
      • 2017-06-03
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 2012-05-11
      相关资源
      最近更新 更多