I have a rather esoteric question to ask, so let me first try to put my question in English and then show some sample code.
Question: I have a handful of classes that are singletons (by keeping track of the number of references). I only allow the classes to be constructed via a _Create() function, which invokes the
new operator if the object does not exist and returns a pointer to the object. Is it possible/safe for me to pass an indefinite number of arguments (via the ellipsis '...') to the _Create() function that in turn passes those arguments to the classes' constructor? In other words, I want to be able to call multiple constructors via the arguments I pass to the _Create() function.
So it's something like this:
Code:
class SKELETON {
private:
static SKELETON *_ref;
static int _ref_count;
SKELETON(); // No-arg constructor
SKELETON(int val); // Constructor with argument
~SKELETON();
SKELETON(const SKELETON& );
SKELETON& operator=(const SKELETON& );
protected:
int value;
;
public:
static SKELETON* _Create(...);
static void _Destroy();
static int _GetRefCount();
void set_value(int val) { value = val; }
int get_value() { return value; }
};
SKELETON* SKELETON::_ref = NULL;
int SKELETON::_ref_count = 0;
inline SKELETON* SKELETON::_Create(...) {
if (_ref == NULL) {
_ref = new SKELETON(...); // Somehow pass the arguments to the constructor
_ref_count = 1;
}
else
_ref_count++;
return _ref;
}
inline void SKELETON::_Destroy() {
if (--_ref_count == 0) {
delete _ref;
_ref = NULL;
}
}
inline int SKELETON::_GetRefCount() {
return _ref_count;
}
int main() {
SKELETON *noarg = SKELETON::_Create(); // Creates class object with default value
SKELETON::_Destroy(); // Deletes the class, since this is the last instance
SKELETON *witharg = SKELETON::_Create(5); // Create the class object with value = 5
SKELETON::_Destroy(); // Memory leaks are bad!
return 0;
}
The code won't compile because passing the ... to the constructor doesn't work. I knew it wouldn't, but I'm not sure how to do this operation. So is this possible/feasible? Thanks for any insight.
