Skip to main content

shared_ptr in C++ | C++ 11


shared_ptr :

Definition: Wraps a reference-counted smart pointer around a dynamically allocated object.

Syntax

template
class shared_ptr; 


The shared_ptr class defines an object that uses reference counting to manage resources. A shared_ptr object effectively holds a pointer to the resource that it owns or holds a null pointer. A resource can be owned by more than one shared_ptr object; when the last shared_ptr object that owns a particular resource is destroyed, the resource is freed.
A shared_ptr stops owning a resource when it is reassigned or reset.


Reference Counting:  It is a technique of storing the number of references, pointers or handles to a resource such as an object, block of memory, disk space or other resources. An object referenced by the contained raw pointer will not be destroyed until reference count is greater than zero i.e. until all copies of shared_ptr have been deleted.
So, we should use shared_ptr when we want to assign one raw pointer to multiple owners.

Example:

// C++ program to demonstrate shared_ptr
#include
#include
using namespace std;

class A
{
public:
    void show()
    {
        cout<<"A::show()"<
    }
};

int main()
{
    shared_ptr p1 (new A);
    cout << p1.get() << endl;
    p1->show();
    shared_ptr p2 (p1);
    p2->show();
    cout << p1.get() << endl;
    cout << p2.get() << endl;

    // Returns the number of shared_ptr objects
    //referring to the same managed object.
    cout << p1.use_count() << endl;
    cout << p2.use_count() << endl;

    // Relinquishes ownership of p1 on the object
    //and pointer becomes NULL
    p1.reset();
    cout << p1.get() << endl;
    cout << p2.use_count() << endl;
    cout << p2.get() << endl;

    return 0;
}



When to use shared_ptr?
Use shared_ptr if you want to share ownership of the resource . Many shared_ptr can point to a single resource. shared_ptr maintains a reference count for this propose. when all shared_ptr’s pointing to resource goes out of scope the resource is destroyed.

Comments

Popular posts from this blog

const used with functions

const used with functions : class Dog {    int age;    string name; public:    Dog() { age = 3; name = "dummy"; }         // const parameters and these are overloaded functions    void setAge(const int& a) { age = a; }    void setAge(int& a) { age = a; }         // Const return value    const string& getName() {return name;}         // const function and these are overloaded functions    void printDogName() const { cout << name << "const" << endl; }  // value of name can't be modified    void printDogName() { cout << getName() << " non-const" << endl; } }; int main() {    Dog d;    d.printDogName();        const Dog d2;    d2.printDogName();     }

Structured Bindings

Returning multiple Values from function C++ 11 vs C++ 17 Returning compound objects Iterating over a compound collection Direct initialization Returning multiple Values from function C++ 11 vs C++ 17 :  C++ 11 (std::tie): std::tuple mytuple() {     char a = 'a';     int i = 123;     bool b = true;     return std::make_tuple(a, i, b);  // packing variable into tuple } To access return value using C++ 11, we would need something like: char a; int i; bool b; std::tie(a, i, b) = mytuple();  // unpacking tuple into variables Where the variables have to be defined before use and the types known in advance. C++ 17 : auto [a, i, b] = mytuple(); Returning compound objects :  This is the easy way to assign the individual parts of a compound type (such as a struct, pair etc) to different variables all in one go – and have the correct types automatically assigned. So let’s have a look at an ...

POST 1 : std::thread in c++ | C++ 11

std::thread   C++  Thread support library std::thread. Threads enable programs to execute across several processor cores. Defined in header Class : thread Member types : native_handle_type Data Member  id    //represents the id of a thread (public member class) Member functions (constructor)    //constructs new thread object (public member function) (destructor)    //destructs the thread object, underlying thread must be joined or detached  (public member function) operator=    //moves the thread object  Observers  // Covered in NEXT POST Operations    // Covered in NEXT POST Constructor :   #include   void f1 ( int n ) { for ( int i = 0 ; i < 5 ; ++ i ) { std:: cout << "Thread 1 executing \n " ; ++ n ; std:: this_thread :: sleep_for ( std:: chrono :: milliseconds ( 10 ) ) ; ...