I'm stepping into unknown territory here (like always). I'm fiddling around with
unions today. So I decided to create a
union that houses a single variable but one that holds 2 values. Internally, the union contains two members:
mPre_buf_) A pointer to an array of
unsigned chars. This buffer is used to store the values.
mT1_data_) A pointer of type
T1 that's used to read from the buffer.
Here's the implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
template <typename T1, const unsigned int tpNo_of_vals = 1>
union Multi_Value
{
public:
Multi_Value(const T1 &pT1_data = T1())
: mPre_buf_(new unsigned char[(tpNo_of_vals * sizeof(T1))])
{
if(mPre_buf_)
{
#if defined DEBUG_MODE
std::cout << "Allocating " << (tpNo_of_vals * sizeof(T1)) << " Bytes\n";
#endif
for(unsigned int I(0); I < tpNo_of_vals; ++I)
mT1_data_ = new(mPre_buf_ + (I * sizeof(T1))) T1(pT1_data);
}
}
~Multi_Value(void)
{
// Delete the objects first.
for(unsigned int I(0); I < tpNo_of_vals; ++I)
(mT1_data_ + I)->~T1();
delete [ ] mPre_buf_;
}
private:
unsigned char *mPre_buf_;
T1 *mT1_data_;
public:
bool operator == (const T1 &pData)
{
for(int I(0); I < tpNo_of_vals; ++I)
{
#if defined DEBUG_MODE
std::cout << "Checking for " << pData << " at address: 0x" << I << '\n';
#endif
if((*(mT1_data_ + I)) == pData)
{
#if defined DEBUG_MODE
std::cout << "Found " << pData << " at address: 0x" << I << '\n';
#endif
return(true);
}
}
return(false);
}
Multi_Value &operator () (const unsigned int &pSlot, const T1 &pData)
{
*(mT1_data_ + pSlot) = pData;
return(*this);
}
};
|
Not the prettiest thing in the world, nor is it the safest, but it's only experimental. Now, the question(s) in hand:
1) Can you see any memory leaks?
2) Can you offer any advice?
Thanks :)
P.S: Please don't suggest the use of any Boost or STL equivalents -- I will ignore such suggestions.
Wazzak