Weak Pointer In C++ - C++ Programming Tutorial
C++ Course / Pointers & References / Weak Pointer In C++

Weak Pointer In C++

BLUF: Mastering Weak Pointer In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Weak Pointer In C++

C++ is renowned for its efficiency. Learn how Weak Pointer In C++ enables low-level control and high-performance computing in the tutorial below.

In this guide, we will explore the concept of a weak pointer in C++ along with its syntax and illustrative instances.

The C++ weakptr represents a standard library feature utilized for holding weak references to objects managed by the sharedptr standard library pointer. This enables the transformation of weakptr to sharedptr when needed to access the referenced object. Once a sharedptr is derived from a weakptr, it provides access to the object. However, it's important to note that a weakptr loses its persistent nature once converted to a sharedptr, existing temporarily. It is recommended not to directly access the weak_ptr before obtaining access to the referenced object.

Syntax:

It has the following syntax:

Example

template< class T > class weak_ptr;

The type managed by the weak pointer is employed for the argument passed as Class T following the C++ weak_ptr function syntax.

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 instance, the shared pointer sharedPtr is referencing an integer containing the value 42. Subsequently, a sharedPtr and a std::weakptrweakPtr are instantiated. When the initial object is no longer present, the Lock method will yield a null shared pointer, which can then be utilized to obtain a shared pointer from a weak pointer.

The software displays the value of the shared object initially when employing the weak pointer for retrieval. Subsequently, the shared pointer is reset, mimicking a situation where the original shared pointer loses control over the object. Following the reset of the shared pointer, the software attempts to retrieve the object once more through 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 code snippet demonstrates how to use the swap function to exchange the weak_ptr when there is a requirement to access the desired resource, as indicated in the output.

In the sharedptr examples, two shared pointers, shrdptr1 and shrdptr2, are initialized with the integers 8 and 10 at the start of the provided code snippet. Initially, the program displays the value stored in shrdptr1, which is 8. Subsequently, both the member function swap and the standard library's swap function are employed to interchange the values held by shrdptr1 and shrdptr2. This operation causes shrdptr_1's value to transition from 8 to 10 and then back to 8.

Within the sharedptr context, the program also establishes two weak pointers, wkptr1 and wkptr2. The value contained in wkptr1, which is 8, is output. Following this, the ownership of wkptr1 and wkptr2 is exchanged using both the member function swap and the swap function from the standard library. Consequently, after the swap, wkptr1 now stores the integer 10. The program concludes by performing another swap between wkptr1 and wkptr2 to revert to the original ownership arrangement. Upon completion of this operation, the value of wkptr_1 is displayed, showing 8 once again.

Conclusion:

The C++ weakptr method is crucial for retrieving and interacting with the elements of a linked list. Furthermore, sharedptr and weakptr collaborate to establish an efficient mechanism for element access. When opting for sharedptr, it is commonly perceived as a lasting action. The C++ weak_ptr method provides several benefits for managing resources effectively.

Input Required

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

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience