DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

shared pointer c++11

std::shared_ptr

It is smart pointer, it is a part of C++11. It shares the object and in other word it implements the “shared ownership” (two or more pointers can point to same object). Technically std::shared_ptr is a class template and class template contains raw pointer (this raw pointer points to object), count variable (it stored the number of shared pointer pointing to object), please check below examples to create a shared pointer:

std::shared_ptr<int> up{new int{5}};
std::shared_ptr<int> up1{up}; //copy constructor
std::shared_ptr<int> up2{nullptr};
up2 = up1;  //Assignment operator
std::cout<<"Int Value:"<<*up2<<std::endl;
std::cout<<"Count:"<<up2.use_count()<<std::endl;//Count:3
//old c++ intialization
std::shared_ptr<std::string>up3(new std::string("digestcpp.com"));

Access the object:

There are 3 ways:

  • *up : using operator* we can access the object.
  • up->: using operator-> we can access the member function of object.
  • up.get(): This function returns the pointer of object.
//Access the object
std::cout<<"Int Value:"<<*up<<std::endl;
int* pIptr= up.get();//return pointer pointing to actual object
std::cout<<"Int value using get():"<<*pIptr<<std::endl;
std::cout<<up3->append(" c++")<<std::endl;

Header file:

#include<memory> under namespace std as std::shared_ptr

Source code with example:

/*
Program:Shared Pointer 
Author: Alpha Master
Date: 21 Feb 2021
*/

//Header File
#include<iostream>
#include<memory>

class A
{
};

int main()
{
    std::cout<<"Shared Pointer"<<std::endl;

    //Shared pointer has int
    std::shared_ptr<int> up{new int{5}};
    std::shared_ptr<int> up1{up}; //copy constructor
    std::shared_ptr<int> up2{nullptr};
    up2 = up1;  //Assignment operator
    std::cout<<"Int Value:"<<*up2<<std::endl;
    std::cout<<"Count:"<<up2.use_count()<<std::endl;
    std::shared_ptr<std::string>up3(new std::string("digestcpp.com"));

    //Access the object
    std::cout<<"Int Value:"<<*up<<std::endl;
    int* pIptr= up.get();//return pointer pointing to actual object
    std::cout<<"Int value using get():"<<*pIptr<<std::endl;
    std::cout<<up3->append(" c++")<<std::endl;
    
    return 0;
}

Output:

Shared Pointer
Int Value:5
Count:3
Int Value:5
Int value using get():5
digestcpp.com c++

Own Shared Pointer class

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer