std::bad_weak_ptr class in C++ with Examples

Standard C++ contains several built-in exception classes, std::bad_weak_ptr is one of them. std::bad_weak_ptr is the type of the object thrown as exceptions by the constructors of shared_ptr that take weak_ptr as the argument, when the weak_ptr refers to an already deleted object. Below is the syntax for the same:

Header File:

<memory>

Syntax:

class bad_weak_ptr: public exception;

Note: To make use of std::bad_weak_ptr, one should set up the appropriate try and catch blocks.

Below are the programs to understand the implementation of std::bad_weak_ptr in a better way:



Program 1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ code for std::bad_weak_ptr
  
#include <bits/stdc++.h>
  
using namespace std;
  
// main method
int main()
{
    shared_ptr<int> gfg1(new int(75));
  
    weak_ptr<int> wp(gfg1);
    gfg1.reset();
  
    // try block
    try {
        shared_ptr<int> gfg2(wp);
    }
  
    // catch block to handle the errors
    catch (const bad_weak_ptr& gfg) {
        cout << gfg.what() << endl;
    }
    return 0;
}

chevron_right


Output:

bad_weak_ptr

Program 2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ code for std::bad_weak_ptr
  
#include <bits/stdc++.h>
  
using namespace std;
  
// main method
int main()
{
    shared_ptr<int> geeksforgeeks(new int(75));
  
    weak_ptr<int> wp(geeksforgeeks);
    geeksforgeeks.reset();
  
    // try block
    try {
        shared_ptr<int
        A_Computer_Science_portal_for_Geeks(wp);
    }
  
    // catch block to handle the errors
    catch (const bad_weak_ptr& gfg) {
        cout << gfg.what() << endl;
    }
}

chevron_right


Output:

bad_weak_ptr

Reference: www.cplusplus.com/reference/memory/bad_weak_ptr/

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.