简体   繁体   中英

References between two smart pointers

Reading this stackoverflow answer :

QWeakPointer - Do you sense a reoccurring pattern? Just as std::weak_ptr and boost::weak_ptr this is used in conjunction with QSharedPointer when you need references between two smart pointers that would otherwise cause your objects to never be deleted.

My question is - could anybody explain me such situation on a simple example, when two referencing smart pointers could cause non-deleted objects?

Thank you in advance..

In the following example, neither of the S objects will ever be destroyed, because the object pointed to by a owns the object pointed to by b , and vice-versa.

struct S {
    std::shared_ptr<S> p;
};

void f()
{
    std::shared_ptr<S> a(new S());
    std::shared_ptr<S> b(new S());
    a->p = b;
    b->p = a;
}

std::weak_ptr is used to break reference cycles. If object lifetime is known to extend beyond the lifetime of the non-owning pointer, raw pointers can be used as well.

The same principles apply to Qt's smart pointers, like QWeakPointer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM