std::weak_ptr Member Functions

The following are some member functions associated with std::weak_ptr to provide different functionalities.

       S.No.                     Functions             Description

1

reset() Clear the weak_ptr.

2

swap Specialization of std:swap(). It swaps the objects managed by weak_ptr.

3

expired()      Check if the resource weak_ptr pointing to exists or not.

4

lock() If the resource pointed by weak_ptr exists, this function returns a shared_ptr with ownership of that resource. If the resource does not exist, it returns default constructed shared_ptr.

5

use_count() Tells about how many shared_ptr owns the resource.

weak_ptr in C++

The weak_ptr is one of the smart pointers that provide the capability of a pointer with some reduced risks as compared to the raw pointer. The weak_ptr, just like shared_ptr has the capability to point to the resource owned by another shared_ptr but without owning it. In other words, they are able to create a non-owning reference to the object managed by shared_ptr.

Similar Reads

Need of weak_ptr

To understand the need for weak_ptr, we need to first understand the use case of shared_ptr which leads to a common problem called a circular link. It occurs when two or more objects reference each other using a shared_ptr. For example, if ObjectA has a shared_ptr to ObjectB and ObjectB has a shared_ptr to ObjectA, they form a circular reference. This can be problematic because neither ObjectA nor ObjectB will ever be deleted, leading to a memory leak....

Syntax of weak_ptr

The weak_ptr can be declared using the following syntax:...

std::weak_ptr Member Functions

The following are some member functions associated with std::weak_ptr to provide different functionalities....

Example of weak_ptr

The following example demonstrates how the weak_ptr solves the circular reference problem....

Applications of weak_ptr

...

Contact Us