Class unique_ptr and Dynamic Memory Allocation - C++ Data Type

C++ examples for Data Type:unique_ptr

Introduction

An object of class unique_ptr maintains a pointer to dynamically allocated memory.

When a unique_ptr object destructor is called and when a unique_ptr object goes out of scope, it performs a delete operation on its pointer data member.

Class template unique_ptr provides overloaded operators * and -> so that a unique_ptr object can be used just as a regular pointer variable is.

Demo Code

 
#include <iostream> 
#include <memory> 
using namespace std; 
     /* w ww  . j  ava2  s .com*/
 class Integer {
  public:
     Integer(int i = 0);
     ~Integer();
 
     void setInteger(int i);
     int getInteger() const;
 
  private:
     int value;
 };
 
 
 Integer::Integer(int i) : value(i) {
     std::cout << "Constructor for Integer " << value << std::endl;
 }
 Integer::~Integer() {
     std::cout << "Destructor for Integer " << value << std::endl;
 }
 // set Integer value
 void Integer::setInteger(int i) { value = i; }
 // get Integer value
 int Integer::getInteger() const { return value; }
// use unique_ptr to manipulate Integer object 
int main() 
{ 
          cout << "Creating a unique_ptr object that points to an Integer\n" ; 
    
          // "aim" unique_ptr at Integer object 
          unique_ptr< Integer > ptrToInteger( new Integer( 7 ) ); 
    
          cout << "\nUsing the unique_ptr to manipulate the Integer\n"; 
          ptrToInteger->setInteger( 99 ); // use unique_ptr to set Integer value 
    
          // use unique_ptr to get Integer value 
          cout << "Integer after setInteger: " << ( *ptrToInteger ).getInteger() ;
}

Result


Related Tutorials