Unique pointer in C++
Feb 27, 2021
Facts of unique pointer
- The unique pointer doesn’t share its memory.
- It can’t be copied to another unique by using an assignment operator.
- The ownership can be moved from one to another.
- “unique ptr” wants to limit the ownership of the object.
Program
#include <iostream>
#include <memory>
using namespace std;
class Demo {
public:
Demo() {
printf("Constructor called\n");
}
void fun() {
printf("Function calling\n");
}
~Demo() {
printf("Destructor called\n");
}
};int main()
{
/* Create unique pointer */
unique_ptr<Demo> ptr (new Demo());
ptr->fun();
printf("***********\n");
/* Move the ownership of the pointer */
unique_ptr<Demo> ptr1 = move(ptr);
ptr1->fun();
}
Output
Constructor calledFunction calling***********Function callingDestructor called