开发者

return boost::shared_ptr question, why destructor got called 3 times

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> o开发者_JAVA技巧bjA(ObjAFactory::createObjA());
    Obj_B objB(objA);
    objB.method1();
}

Output:

*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*


When createObjA returns, the shared_ptr goes out of scope and destructs the object. You're now returning an invalid pointer.

The Obj_B constructor is taking a copy of the pointer. When that object is destroyed, the shared_ptr will try to destroy it again.

When main() exits, the third shared_ptr is destroyed and another attempt is made to destroy the invalid pointer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜