【发布时间】:2018-04-28 05:54:04
【问题描述】:
我正在构建一个模板类向量,我遇到了错误“malloc:error for object xxxxxxxxx: pointer being freed was not assigned”但我无法确定我的错误在哪里。这些方法是我实现的唯一使用变量 T *data 的方法。
template <class T>
class vector
{
public:
// constructors and destructors
vector() { numElements = 0; numCapacity = 0; }
vector(int num) throw (const char *);
vector(const vector & rhs) throw (const char *);
~vector() { delete [] data; }
vector & operator = (const vector & rhs) throw (const char *);
int size() const { return numElements; }
int capacity() const { return numCapacity; }
bool empty() const { return numElements == 0 ? true : false; }
T & operator [] (int index) throw (const char *)
{
return data[index];
}
const T & operator [] (int index) const throw (const char *)
{
return data[index];
}
private:
T * data;
int numElements;
int numCapacity;
};
这是我的复制构造函数,没有默认构造函数和赋值运算符
template <class T>
vector <T> & vector <T> :: operator = (const vector <T> & rhs)
throw (const char *)
{
if (rhs.size() == 0) {
this->data = NULL;
numElements = 0;
numCapacity = rhs.capacity();
return *this;
}
if (numCapacity < rhs.numElements) {
try {
data = new T[rhs.numElements];
} catch(std::bad_alloc) {
throw "ERROR: Unable to allocate buffer";
}
for (int i = 0; i < numCapacity; i++)
data[i] = rhs.data[i];
}
return *this;
}
template <class T>
vector <T> :: vector(const vector <T> & rhs) throw (const char *)
{
assert(rhs.capacity() >= 0);
if (rhs.numCapacity == 0)
{
numCapacity = 0;
numElements = 0;
this->data = NULL;
return;
}
try
{
data = new T[rhs.numCapacity];
}
catch (std::bad_alloc)
{
throw "ERROR: Unable to allocate buffer";
}
numCapacity = rhs.numCapacity;
numElements = rhs.size();
for (int i = 0; i < numCapacity; i++)
data[i] = rhs.data[i];
}
template <class T>
vector <T> :: vector(int num) throw (const char *)
{
assert(num >= 0);
numElements = 0;
if (num == 0)
{
numCapacity = 0;
this->data = NULL;
return;
}
// attempt to allocate
try
{
data = new T[num];
}
catch (std::bad_alloc)
{
throw "ERROR: Unable to allocate buffer";
}
numCapacity = num;
}
非常感谢任何帮助
【问题讨论】:
标签: c++ templates pointers malloc