
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
RAII and Smart Pointers in C++
RAII in C++
RAII (Resource Acquisition Is Initialization) is C++ technique which control the life cycle of resource. It is a class variant and is tied to object life time.
It encapsulates several resources into class where resource allocation is done by constructor during object creation and resource deallocation is done by destructor during object destruction.
Resource is guaranteed to be held till the object is alive.
Example
void file_write { Static mutex m; //mutex to protect file access lock_guard<mutex> lock(m); //lock mutex before accessing file ofstream file("a.txt"); if (!file.is_open()) //if file is not open throw runtime_error("unable to open file"); // write text to file file << text << stdendl; }
Smart Pointers in C++ & minus;
Smart pointer is an abstract data type by using which we can make a normal pointer in such way that it can be used as memory management like file handling, network sockets etc., also it can do many things like automatic destruction, reference counting etc.
Smart pointer in C++, can be implemented as template class, which is overloaded with * and -> operator. auto_ptr, shared_ptr, unique_ptr and weak_ptr are the forms of smart pointer can be implemented by C++ libraries.
Example
#include <iostream> using namespace std; // A generic smart pointer class template <class T> class Smartpointer { T *p; // Actual pointer public: // Constructor Smartpointer(T *ptr = NULL) { p = ptr; } // Destructor ~Smartpointer() { delete(p); } // Overloading de-referencing operator T & operator * () { return *p; } // Over loading arrow operator so that members of T can be accessed // like a pointer T * operator -> () { return p; } }; int main() { Smartpointer<int> p(new int()); *p = 26; cout << "Value is: "<<*p; return 0; }
Output
Value is: 26