unique_ptr in C++
In this tutorial, we will learn how to use unique_ptr in C++. We will learn about the unique_ptr in C++, what exactly it is and with an example.
The unique_ptr is one of the smart pointers in C++. We specify it unique_ptr< >
, where inside < > we specify the type that can be user-defined or pre-defined. The up_var is the unique pointer name.
Syntax :
unique_ptr<type> up_var;
There is no need to clean the memory in an explicit manner. The unique pointer will take of it whenever it goes out of the scope. However, whenever we use the unique pointer variable its value cannot be assigned to another unique pointer. As we can figure it out from its name.
In a unique pointer, we cannot assign the ownership to any other pointer.
Example:
//illustrating the use of unique_ptr in C++ #include<iostream> #include<memory> using namespace std; //defining the structure named Uni_p struct Uni_p{ //Constructor Uni_p(){ cout<<"\nInside Constructor"; } //Destructor ~Uni_p(){ cout<<"\nInside destructor"; } }; //Main function starts from here int main() { cout<<"\nInside Main"; //declared and intialized an unique pointer unique_ptr<Uni_p> UP1 (new Uni_p); //unique_ptr<Uni_p> UP2 = UP1; cout<<"\nExit from main"; return 0; }
The above program produces the output as,
Inside Main Inside Constructor Exit from main Inside destructor
In the program, we can see one comment line i.e.,
unique_ptr<Uni_p> UP2 = UP1;
If we remove the comment symbol // from it, then execute the program therefore it results in an error. As we cannot change the ownership from one unique pointer to another. If we want to change the ownership we can make use of the shared pointer (shared_ptr) which is also one of the smart pointers in C++.
Also read:
Advantages of reference variables over pointer variables in C++
Leave a Reply