"mati-006" <lo********@gazeta.NOSPAM.pl> wrote in message
news:e7**********@inews.gazeta.pl...
Hi
Short question for which I can't find answer:
I want to initialize the array of objects with the same values.
new MyType[n]; calls default constructor
new MyType(val1, val2); initializes only one element
Is there any way to merge these two things?
Now I have something like this:
p = new MyType[n];
for(int i=0;i<n;i++) p[i].init(val1,val2);
And this is ugly to me...
maybe what you want is this:
std::vector<SmartPtr<MyType> > sVector(32);
for (unsigned int i = 0, iMax = sVector.size(); i < iMax; i++)
sVector[i] = MyType::CreateElement(val1, val2);
template<class T>
class SmartPtr
{ private:
T *m_p;
public:
SmartPtr(void)
:m_p(0)
{
}
SmartPtr(T *_p)
:m_p(_p)
{ if (m_p)
m_p->AddRef();
}
SmartPtr(const SmartPtr<T> &_r)
:m_p(_r.m_p)
{ if (m_p)
m_p->AddRef();
}
~SmartPtr(void)
{ if (m_p)
m_p->Release();
}
operator=(const SmartPtr &_r)
{ if (m_p)
m_p->Release();
if (m_p = _r.m_p)
m_p->AddRef();
return *this;
}
operator T *(void) const
{ return m_p;
}
};
class MyType
{ private:
mutable unsigned int m_iRefCount;
double m_dVal1, m_dVal2;
MyType(void)
:m_iRefCount(0)
{
};
MyType(double _dVal1, double _dVal2)
:m_iRefCount(0),
m_dVal1(_dVal1),
m_dVal2(_dVal2)
{
}
virtual ~MyType(void)
{ assert(!m_iRefCount);
}
public:
void AddRef(void) const
{ m_iRefCount++;
}
void Release(void) const
{ assert(m_iRefCount);
--_iRefCount;
if (!m_iRefCount)
delete this;
}
SmartPtr<MyType> CreateElement(double _dVal1, double _dVal2)
{ return new MyType(_dVal1, _dVal2);
}
};
The class SmartPtr is a general class.
The methods AddRef() and Release() could be part of a general base class
(the destructor should be virtual).
Of course
std::vector<MyType*> sVector(32);
would also work -- but in this case I would rather write a derived class
from std::vector which cleans up the pointers inside the destructor, e.g.
template<class T>
class PtrVector:public std::vector<T>
{ public:
PtrVector(unsigned int _iSize = 0)
:std::vector(_iSize)
{
}
~PtrVector(void)
{ for (unsigned int i = 0, iMax = size(); i < iMax; i++)
delete (*this)[i];
}
};