số 20 quá nhỏ, sizeof temp quá nhỏ
==> nên dùng khai báo
int a[20];
temp x(5);
Dùng cấp phát động sẽ làm ct chậm hơn và làm hổng bộ nhớ
Mà tốt nhất là các bạn nên tránh cấp phát động, chỉ dùng khi thực sự cần thiết, và nên gom tất cả các phát biểu new về một mối
Ví dụ
Thay vì mỗi lần cần cấp phát bộ nhớ tui lại gọi new ở nhiều chỗ rải rác thì
tui viết ra 1 lớp Buffer để qunả lý
Code:
template <class T>
class SafeBuffer
{
protected:
T* m_pAlloc;
unsigned int m_iAllocLen;
unsigned int m_iCapacity;
void CopyBuffer(T* pDes, const T* pSrc, unsigned int iLen, bool bIsAssignedOBO)
{
if (pDes == pSrc || pSrc == NULL || pDes == NULL || iLen <= 0) return;
if (bIsAssignedOBO)
{
for (unsigned int i = 0; i < iLen; ++i)
{
pDes[i] = pSrc[i];
}
}
else
memcpy(pDes, pSrc, iLen*sizeof T);
}
const SafeBuffer<T>& Assign (const SafeBuffer<T> &other, bool bIsOBO)
{
Alloc(other.m_iAllocLen);
CopyBuffer(m_pAlloc, other.m_pAlloc, m_iAllocLen, bIsOBO);
m_iAllocLen=other.m_iAllocLen;
return *this;
}
void InitDefault()
{
m_pAlloc = NULL;
m_iAllocLen = 0;
m_iCapacity = 0;
}
public:
SafeBuffer()
{
InitDefault();
}
SafeBuffer(const SafeBuffer<T> &other, bool bIsOBO = false)
{
m_pAlloc=NULL;
Assign(other, bIsOBO);
}
const SafeBuffer<T>& Assign (const SafeBuffer<T> &other)
{
return Assign(other, false);
}
const SafeBuffer<T>& AssignOBO (const SafeBuffer<T> &other)
{
return Assign(other, true);
}
T* GetPointer()
{
if (IsNull()) return NULL;
return m_pAlloc;
}
const T* GetPointer() const
{
if (IsNull()) return NULL;
return m_pAlloc;
}
unsigned int GetCapacity() const
{
return m_iCapacity;
}
unsigned int GetAllocLen() const
{
return m_iAllocLen;
}
bool IsNull() const
{
return (m_pAlloc == NULL || m_iAllocLen <= 0);
}
T* Alloc(unsigned int iAllocLen)
{
if (iAllocLen <= m_iCapacity)
{
m_iAllocLen = iAllocLen;
return GetPointer();
}
Free();
m_pAlloc = new T[iAllocLen];
m_iAllocLen = iAllocLen;
m_iCapacity = iAllocLen;
return GetPointer();
}
void LazyFree()
{
m_iAllocLen = 0;
}
void Free()
{
delete[] m_pAlloc;
InitDefault();
}
const SafeBuffer<T>& operator = (const SafeBuffer<T> &other)
{
return AssignOBO(other);
}
virtual ~SafeBuffer()
{
Free();
}
};
Code rất đơn giản nhưng lại vô cùng tiện ích (code này là code xịn đấy nhá, đã chạy thương mại gần chục năm rrồi)
Ví dụ
SafeBuffer<char> buf;
char *strYourName = buf.Alloc(1024); //hoặc buf.Alloc(1024); strYourName = buf.GetPointer();
//xử lý strYourName...
//xong rồi, khỏi cần quan tâm delete