Saturday, July 12, 2008

C++ Challenge of the Month: July 2008

Starting this month, I would be posting a C++ programming problem, and it's solution every month in a series called C++ Challenge of the Month (CCOM). The solution will be posted a couple of weeks after the problem and in the meanwhile, I hope to see a few readers try their hand at the problem. So here we go.


CCOM #1: Write the outline of a smart pointer class capable of managing pointers to classes from hierarchies which don't have a virtual destructor

Need a smart pointer, which can be used like:

smart_ptr<base> p = new derived;

When p goes out of scope, the object must be deleted and the destructor of derived must be called, irrespective of whether ~base() is virtual or not.

Courtesy, Syam Krishnan, Thiruvananthapuram, Kerala.





1 comment:

valker said...

note: i use "{" "}" instead of "<" and ">".

#include {iostream}

class base {
};

class derived : public base {
public:
~derived() { std::cout << "~derived\n"; }
};

class tmp_base {
public:
virtual void destroy(){}
};

template {class DERIVED}
class tmp : public tmp_base {
DERIVED* p_;
public:
tmp(DERIVED* p) : p_(p) {}
virtual void destroy() { delete p_; }
};

template{class BASE}
class smart_ptr {
tmp_base* tmp_;
public:
template{class DERIVED}
smart_ptr(DERIVED* pd) : tmp_(new tmp{DERIVED}(pd)) {}
~smart_ptr() { tmp_->destroy(); delete tmp_; }
};

int main(int argc, _TCHAR* argv[])
{
volatile int i = 1;
if(i == 1) {
smart_ptr{base} p(new derived);
}
return 0;
}