Unique pointer in C++

  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.
#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();


}
Constructor calledFunction calling***********Function callingDestructor called

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store