c++ - 类模板的问题

标签 c++ templates

我有作业要做,但我对类模板不是很熟悉。

任务是:

There's a major problem in the implementation of the following class. Can you spot it? How can you fix the problem? You can propose more than one solution, depending on the requirement specifications of the class.

    template <class T>
class Array
{
private:
    T *m_pData;
    unsigned int m_nSize;

public:
  Array(unsigned int nSize) : m_nSize(nSize)
  {
    if(m_nSize > 0)
      m_pData = new T[m_nSize];
  }

virtual ~Array()
  {
    if(m_pData != NULL)
      delete m_pData;
  }
bool Set(unsigned int nPos, const T& Value)
  {
    if(nPos < m_nSize)
    {
      m_pData[nPos] = Value;
      return true;
    }
    else
      return false;
  }

  T Get(unsigned int nPos)
  {
    if(nPos < m_nSize)
      return m_pData[nPos];
    else
      return T();
  }
};

据我所知,存在内存泄漏。你发现其他问题了吗?提示比准确的答案更受欢迎;)

最佳答案

  1. 构造函数-当nSize为0时需要设置m_pData的值
  2. 您可以删除空指针,因此析构函数中不需要 if 语句。删除应该是delete[]

关于c++ - 类模板的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7067792/

相关文章:

c++ - < 运算符在不应该返回 true 时返回 true

c++ - 将 C++ 11 的 for-range 语法用于顺序对的方法?

C++ 在编译时用 constexpr char 数组指针分配静态数组?

templates - 动态 ConfigMap Helm 模板

c++ - QTableWidget 中的 QComboboxes

c++ - C 与 C++ 在内存分配方面的性能

C++ 我应该使用转发引用吗?

c++ - 无法在类中使用以数组作为参数的函数模板

c++ - 为什么只有一些 C++ 模板实例导出到共享库中?

c++ - 汇编最大整数除法