Allow objects to be allocated only using dynamic allocation [closed]
-
23-12-2020 - |
Question
I am working on a small library, where I have following requirements for any class X
:
class X
must be allocatable only usingoperator new
- All the children of
class X
should implicitly become allocatable only byoperator new
- The syntax for heap allocation should be elegant
- Not much of the existing code should be changed to incorporate this
- 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)]
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