Posts

Showing posts from June, 2012

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 K-Shortest Paths Algorithm in C++

Image
Introduction Following on from a previous post which was concerned with finding all possible combinations of paths between communicating end nodes, this algorithm finds the top k number of paths: first the shortest path, followed by the second shortest path, the third shortest path, and so on, up to the k-th shortest path.