return boost :: shared_ptr问题,为什么析构函数被调用了3次

时间:2010-10-05 19:36:46

标签: shared-ptr

class Obj_A {
public:
    ~Ojb_A() {
         cout << "calling Obj_A() destructor\n";
     }
    void method1() {
         cout << "invoking Obj_A::method1()\n";
    }
};

class Obj_B {
    boost::shared_ptr<Obj_A> _objA;
public:
    Obj_B(Obj_A *objA) {
        _objA.reset(objA)
     }

    void method1() { _objA->method1(); }
};

class ObjAFactory {
public 
    static Obj_A* createObjA();
};

Obj_A* ObjAFactory::createObjA() {
    boost::shared_ptr<Obj_A> objA(new Obj_A());
    return objA.get();
}

void main() {
    boost::shared_ptr<Obj_A> objA(ObjAFactory::createObjA());
    Obj_B objB(objA);
    objB.method1();
}

输出:

*calling Obj_A() destructor
invoking Obj_A::method1()
calling Obj_A() destructor
calling Obj_A() destructor
a.out in free(): warning: page is already free
a.out in free(): warning: page is already free*

1 个答案:

答案 0 :(得分:0)

createObjA返回时,shared_ptr超出范围并破坏对象。你现在正在返回一个无效的指针。

Obj_B构造函数正在获取指针的副本。当该对象被销毁时,shared_ptr将尝试再次销毁它。

main()退出时,第三个shared_ptr被销毁,另一次尝试销毁无效指针。