Question

I am working on a small library, where I have following requirements for any class X:

  1. class X must be allocatable only using operator new
  2. All the children of class X should implicitly become allocatable only by operator new
  3. The syntax for heap allocation should be elegant
  4. Not much of the existing code should be changed to incorporate this
  5. After some point of time, if I want to allow class X to be allocatable as automatic; again not much code should be changed

I also welcome C++0x solutions (for future use only).

[Note: I have done my part of research and will be posting it as an answer (tested for basic scenarios)]

Was it helpful?

Solution

// Dynamic.h
class OnlyDynamic
{
  template<class T> friend struct Dynamic;
  virtual void*** __Restriction () = 0;
};

template<class T>
class Dynamic : public T
{ 
  virtual void*** __Restriction () { return 0; }
  ~Dynamic();
public:
#ifdef Cpp0x
  template<typename... Args>
  Dynamic(Args... args) : T(args...) {}
#else
  Dynamic () {}
  template<typename A1> Dynamic(const A1 &a1) : T(a1) {}
  template<typename A1, typename A2> Dynamic(const A1 &a1, const A2 &a2) : T(a1,a2) {}
//...
  template<typename A1, typename A2, typename A3, typename A4, typename A5, typename A6>
  Dynamic(const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5, const A6 &a6) : T(a1,a2,a3,a4,a5,a6) {}
#endif 
};

Usage:


Suppose, I want to make class X only dynamically allocatable; I should simply derive OnlyDynamic (access specifier doesn't matter) and allocate with new Dynamic<X>().

Example:

class Base {};

struct A : Base, OnlyDynamic  // <-- only inherit
{
  A (int i) {}
};

A *p = new Dynamic<A>(3);
delete p;

As of now, I am seeing all the given requirements getting fulfilled with this solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top