智能指针不够智能

时间:2012-09-05 11:36:37

标签: c++ smart-pointers

以下是一个例子:

template<typename T>
struct smart { //Smart Pointer class
    smart();
    ~smart();
    smart(const smart& copy);
    T* target;
    int count;
};

struct atest {
    smart<atest> next;
};

void Garbage() {
    smart_ptr<atest> Test=smart<atest>(new atest);
//Test.count == 1
    Test->next=Test;
//Test.count == 2
//Test.target == Test->next.target
}
//Test.count == 1
//Test'll never be deleted! because it contains itself.

int main() {
    for (int i=0;i<10000000;i++) {
        Garbage();
    }
}

Test方法结束后,{@ 1}}可以让Garbage删除自己吗? 这是另一个问题,Smart Pointers还有另一个漏洞吗?

1 个答案:

答案 0 :(得分:2)

你的问题很模糊,但我认为这是关于循环引用,你应该使用“弱”智能指针以避免这种情况。您可以使用weak_ptr here了解有关如何打破周期的更多信息。