Posts

Showing posts with the label memory management

Creating smart pointers in C++

Introduction What are smart pointers? They are a means of handling the problems associated with normal pointers, namely memory management issues like memory leaks, double-deletions, dangling pointers etc. This post gives a simple guide to creating your own smart pointer in C++. As a simple starting example, consider a basic template class which can be used to hold generic data types: [code language="cpp"] template <class T> class Ptr { public: Ptr(T* d) { data = d;} private: T* data; }; [/code] And also consider an example class A which we will use the the smart pointer to hold: [code language="cpp"] class A { public: A() {} ~A() {} void DoStuff() { std::cout << "Hello"; } }; [/code] One often-encountered problem is that of forgetting to delete. Or maybe some exception gets thrown and the function is never given the chance to delete. Either way, the result is a memory leak, as would be the case in the following fun...

The Big Three in C++

Constructor, destructors and assignment operators There is a rule of thumb in C++ that if a class defines a destructor, constructor and copy assignment operator - then it should explicitly define these and not rely on their default implementation. Why do we need them? In the example below, the absence of an explicit copy constructor will simply make an exact copy of the class and you end up with two classes pointing to the same memory address - not what you want.  When you delete the array pointer in one class for example, the other class will be pointing to memory to which you have no idea as what it contains. Consider the following example class which is used to house an array of integers plus its size. It is written in such a way as to guarantee a crash: [code language="cpp"] #include ,algorithm> class Array { private: int size; int* vals; public: ~Array(); Array( int s, int* v ); }; Array::~Array() { delete vals; vals = NULL; ...

Avoiding Memory Leaks using Boost Libraries

Using boost::scoped_array When we want to dynamically allocate an array of objects for some purpose, the C++ programming language offers us the new and delete operators that are intended to replace the traditional malloc() and free() subroutines that are part of the standard library :

Using Smart Pointers to Avoid Memory Leaks

Using boost::scoped_array When we want to dynamically allocate an array of objects for some purpose, the C++ programming language offers us the new and delete operators that are intended to replace the traditional malloc() and free() subroutines that are part of the standard library :