Weak Pointer In C++

In this article, we will discuss the weak pointer in C++ with their syntax and examples.

The C++ weakptr is a standard library component. It is used to store weak references to any objects controlled by the sharedptr standard library pointer, which is used to ultimately transform weakptr to sharedptr . The sharedptr that was ultimately created from the weakptr is used to access the referenced object. A weakptr loses its capacity to remain forever after it is transformed into a sharedptr , indicating that it only exists momentarily. It is not advised to access weak_ptr first before granting access to the reference object.

Syntax:

It has the following syntax:

Example

template< class T > class weak_ptr;

The type controlled by the weak pointer is used for the parameter supplied as Class T according to the syntax for the C++ weak_ptr function.

How does C++'s weak_ptr operate?

Every pointer in a high-level language is primarily used to reference objects and subsequently access elements that are available in an array in a well-organized style. Similar circumstances apply to C++'s weakptr . The weakptr working flow is described throughout the class template:

  • The weak_ptr used for referencing an object initially is not the actual pointer, as it is considered as a temporary pointer in terms of object referencing and assigning.
  • However, once weakptr gains final control or authority over shareptr , object accessing and referencing become simple and efficient.
  • The main purpose of this coordination and sharing , and switching between the weakptr and shareptr for reading and referencing, is to prevent lengthy cycles within the data structure.
  • When shareptr assumes full responsibility for managing resources during resource allocation and analysis, weakptr loses all control and is erased.
  • A weakptr never allows access to the elements directly; instead, it uses the sharedptr object , which owns the complete code, to call the member function Lock to access the code that needs to use the resource.
  • Once the Lock or weakptr is called for resource allocation or to control any bLock, an empty weakptr object is generated.
  • Once the Lock or the weakptr is jointly referenced or held by the majority of the sharedptr object , one complete cycle has been accomplished or finished.
  • Instead of merely employing weakptr , which is a component of the complete working format of pointers in any of the pointer concepts, it makes use of all resources prominently with the aid of shareptr .
  • The sharedptr makes use of the weakptr's behaviour of obtaining Locks and weakptr's points to make the end resources freed and released by the weakptr .
  • The list and its related nodes will also be easily deleted and distinguished once all the aforementioned resources have been released, creating an optimized method of analysis and format sizing.
  • This complete cycle consists of numerous checks and methods, including the expired method , which is used to determine whether or not ownership has expired.
  • By using Lock , you can take an individual, exclusive Lock over a resource, preventing other resources from trying to target it and causing conflicts in their attempts to do so.
  • The weak_ptr pointing is checked using the owner before, which returns true if icpp tutorials correctly.
  • Within that entire cycle, the owned resource is released using Reset .
  • A swap technique is used when two weak_ptr are acting on the objects.
  • The number of sharedptr objects is counted and tracked using the usecount
  • The technique for swapping out the initially owned resources is operator= .
  • Examples of weak_ptr in C++:

Here are some examples of weak_ptr in C++:

Example - 1:

Example

#include <iostream>
#include <memory>

int main() {
std::shared_ptr<int>sharedPtr = std::make_shared<int>(42);

std::weak_ptr<int>weakPtr = sharedPtr;

    if (auto LockedPtr = weakPtr.Lock()) {
        // Use the weak pointer's shared object
std::cout<< "Weak pointer value: " << *LockedPtr<< std::endl;
    } else {
std::cout<< "Weak pointer is expired" << std::endl;
    }

sharedPtr.reset(); // The shared pointer is reset, object may be deleted

    if (auto LockedPtr = weakPtr.Lock()) {
std::cout<< "Weak pointer value after reset: " << *LockedPtr<< std::endl;
    } else {
std::cout<< "Weak pointer is expired after reset" << std::endl;
    }

    return 0;
}

Output:

Output

Weak pointer value: 42
Weak pointer is expired after reset

Explanation:

In this example, the shared pointer sharedPtr points to an int with the value 42 . After that, a sharedPtr and a std::weakptrweakPtr are created. If the original object has been removed, the Lock function returns an empty shared pointer, which is used to retrieve a shared pointer from a weak pointer.

The program prints the shared object's value first when it uses the weak pointer to access it. After that, the shared pointer is reset , simulating a scenario in which the initial shared pointer no longer controls the object. After resetting the shared pointer, the program tries to access the object again using the weak pointer.

Example - 2:

Example

#include <memory>
#include <iostream>

int main() {
    // Creating a shared pointer to an int with value 14
std::shared_ptr<int>sharedPtr(new int(14));

    // Creating a weak pointer that shares ownership with the shared pointer
std::weak_ptr<int>weakPtr(sharedPtr);

    // Accessing the object using the weak pointer's Lock() function
    // The shared object is still alive, so this will succeed
std::cout<< "Acquired weak_ptr through Lock(): " << *weakPtr.Lock() << std::endl;

    // Checking if the weak pointer is expired
    // Since the shared object is still alive, this will output "false"
std::cout<< "Weak pointer expired: " << std::boolalpha<<weakPtr.expired() << std::endl;

    // Resetting the weak pointer
weakPtr.reset();

    // Checking if the weak pointer is expired after reset
    // Since we reset the weak pointer, it's no longer associated with any object
    // This will output "true"
std::cout<< "Weak pointer expired after reset: " << std::boolalpha<<weakPtr.expired() << std::endl;

    return 0;
}

Output:

Output

Acquired weak_ptr through Lock(): 14
Weak pointer expired: false
Weak pointer expired after reset: true

Example - 3:

Example

#include <memory>
#include <iostream>

int main() {
    // Creating a shared pointer to an int with value 8
std::shared_ptr<int> sharedPtr1(new int(8));

    // Creating a weak pointer that shares ownership with the shared pointer
std::weak_ptr<int>weakPtr(sharedPtr1);

std::cout<< "Count of sharedPtr1: " << sharedPtr1.use_count() << std::endl;
std::cout<< "Count of weakPtr: " <<weakPtr.use_count() << std::endl;

    // Creating another shared pointer that shares ownership with sharedPtr1
std::shared_ptr<int> sharedPtr2(sharedPtr1);

std::cout<< "Count of sharedPtr1 after sharedPtr2 creation: " << sharedPtr1.use_count() << std::endl;
std::cout<< "Count of weakPtr after sharedPtr2 creation: " <<weakPtr.use_count() << std::endl;

    return 0;
}

Output:

Output

Count of sharedPtr1: 1
Count of weakPtr: 1
Count of sharedPtr1 after sharedPtr2 creation: 2
Count of weakPtr after sharedPtr2 creation: 2

Example - 4:

Example

#include <memory>
#include <iostream>
int main()
{
std::shared_ptr<int> shrd_ptr_1(new int(8));
std::shared_ptr<int> shrd_ptr_2(new int(10));
std::cout<< "*shrd_ptr_1 == " << *shrd_ptr_1 << std::endl;
shrd_ptr_1.swap(shrd_ptr_2);
std::cout<< "*shrd_ptr_1 == " << *shrd_ptr_1 << std::endl;
swap(shrd_ptr_1, shrd_ptr_2);
std::cout<< "*shrd_ptr_1 == " << *shrd_ptr_1 << std::endl;
std::cout<< std::endl;
std::weak_ptr<int> wk_ptr_1(shrd_ptr_1);
std::weak_ptr<int> wk_ptr_2(shrd_ptr_2);
std::cout<< "*wk_ptr_1 == " << *wk_ptr_1.Lock() << std::endl;
wk_ptr_1.swap(wk_ptr_2);
std::cout<< "*wk_ptr_2 == " << *wk_ptr_2.Lock() << std::endl;
swap(wk_ptr_1, wk_ptr_2);
std::cout<< "*wk_ptr_1 == " << *wk_ptr_1.Lock() << std::endl;
return (0);
}

Output:

Output

*shrd_ptr_1 == 8
*shrd_ptr_1 == 10
*shrd_ptr_1 == 8

*wk_ptr_1 == 8
*wk_ptr_2 == 10
*wk_ptr_1 == 8

Explanation:

This program shows how to utilize the swap method to swap the weak_ptr when it's necessary to get the needed resource, as seen by the output.

In the sharedptr instances, the shrdptr1 and shrdptr2 thacpp tutorial to the integers 8 and 10 are created at the beginning of the supplied program. After that, the value of shrdptr1 (which is 8 ) is printed. Next, it uses both the member function swap and the swap function from the standard library to swap the contents of shrdptr1 and shrdptr2 . As a result, shrdptr1's value shifts from 8 to 10 and back again. As part of the sharedptr instances, the program creates two weakptr instances, wkptr1 and wkptr2. wkptr1's value , 8, is printed by t . After that, the ownership of wkptr1 and wkptr2 are switched using the member function swap and the swap function from the standard library. After the values of wkptr1 and wkptr2 are switched, wkptr1 now contains the number 10 . The program ends by switching wkptr1 and wkptr2 once more to return to the previous ownership. After that, the value of wkptr_1 is printed, which returns 8 .

Conclusion:

The C++ weakptr function is essential for obtaining and accessing the list node's elements. Additionally, sharedptr and weakptr work together to create an optimized cycle for accessing the elements. Once sharedptr has been chosen, it is generally thought of as a permanent operation. The C++ weak_ptr function offers numerous advantages for resource acquisition.

Input Required

This code uses input(). Please provide values below: