看到一個挺有趣的code,可以自動分配記憶體大小,還有可隨時變動大小:
template <class T>class Z
{
private:
T* m_space;
size_t m_size;
public:
Z(size_t size = 0)
{
if (size == 0)
size = 1;
m_space = new T[size];
memset(m_space, 0, size * sizeof(T));
m_size = size;
}
~Z()
{
delete[] m_space;
}
operator T*()
{
return m_space;
}
size_t GetMemSize()
{
return m_size * sizeof(T);
}
size_t GetSize()
{
return m_size;
}
void _clear()
{
memset(m_space, 0, m_size * sizeof(T));
}
void Resize(size_t new_size)
{
if (new_size == m_size)
return; // same size
// Create buffer to store existing data
T* new_space = new T[new_size];
size_t new_space_mem_size = new_size * sizeof(T);
memset((void*)new_space, 0, new_space_mem_size);
if (m_size < new_size)
// we created a larger data structure
memcpy((void*)new_space,m_space,m_size * sizeof(T));
else
// we created a smaller data structure
memcpy((void*)new_space,m_space,new_size * sizeof(T));
delete[] m_space;
m_space = new_space;
m_size = new_size;
}
void AddResize(size_t More)
{
Resize(m_size + More);
}
};
使用的時候:
Z<char> XD(10);
sprintf_s(XD, 10, "Test\n");
printf_s("%c", XD[0]);
printf_s("%s", XD);
還有其他的運用就是,挺好玩的~
0 意見:
張貼留言