智能指针不够智能

Smart Pointer isn't smart enough

本文关键字:智能 不够 指针      更新时间:2023-10-16

下面是一个例子:

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();
    }
}

有没有办法让TestGarbage方法结束后删除自己?还有一个问题,智能指针还有其他漏洞吗?

你的问题很模糊,但我认为这是关于循环引用的,你应该使用"弱"智能指针来避免这种情况。您可以在这里阅读更多关于如何使用weak_ptr打破循环的信息。