Unique pointer in C++

Dineshbaburam
Feb 27, 2021

Facts of unique pointer

  1. The unique pointer doesn’t share its memory.
  2. It can’t be copied to another unique by using an assignment operator.
  3. The ownership can be moved from one to another.
  4. “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

--

--