what a shared pointer is in C++

 Well a shared pointer is a type of smart pointer. Usually typed like this shared_ptr .

That is generally how a C++ std::shared_ptr is on a syntax level.  What a shared pointer generally is a smart pointer that provides ownership dynamically allocated object of type T. Multiple shared_ptr instances can own the same object. The object is destroyed automatically when the last shared_ptr owning it is destroyed or reset. 

Key Properties

    * Ownership: shared (reference counted).

    * Lifetime: deterministic destruction when reference count reaches zero.

    * Thread-safety: incrementing/decrementing the control block's count is

       atomic (so different shared_ptr objects can be used concurrently), 

        but accessing the pointed to object is not synchronized by shared_ptr.

    *  Controls both pointer and metadata via a control block

        (manages reference counts and optionally custom deleter/weak count

        allocator) .

    *  Works with std::weak_ptr to break reference cycles.

 Control Block

A shared_ptr holds:

    * A raw pointer to the managed object (T*).

    * A pointed to a control block (implementation detail) which contains:

        * shared use count: number of shared_ptr instances owning the object*

        * Weak count: Number of weak_ptr instances observing the object 

          (Plus one shared count> 0 typical implementations).

        * Deleter and allocator (if provided). The control block lifetime extends

          until both shared and weak counts reach zero*.

Basic usage examples

    1 Creating and basic operations

cpp example

 #include <memory>

auto p = std::make_shared<int>(42);

block + objectstd::shared_ptr<int> q = p;

(p) { /* checks non-null */ }int val = *p;

dereferencep.reset();

// release the owner; destroyed when use_count()==0

    2 From raw pointer not preferred

cpp example

 std::shared_ptr<int> (a new int(5));

// works, but risk to allocations and exception safety issues

    3 Custom deleter

cpp example

auto deleter = [](FILE* f){ if(f) std::fclose(f); };std::shared_ptr<FILE>

fp(std::fopen("file.txt","r"), deleter);

    4 Using weak_ptr

cpp example

std::weak_ptr<int> w = p;

I hope you enjoyed this post and my code snip it examples.  

Comments

Popular posts from this blog

Systemd alternatives for Linux