我正在尝试学习更多C ++!经过一段时间的内存分配,我到达了一个难以理解的地方。
我编写了一种代码(对于某个类的对象),可以很好地使用(不是很确定,但至少不会显示任何内存冲突),但是对于类似的初始化,它会崩溃。
[如果有人可以解释我的情况以及如何解决此问题,我将不胜感激。
我的想法:问题出在下面,因为在有问题的初始化中我只分配了一个对象而不是数组,所以我试图删除已分配对象的数组。
delete[] pointer; //PROBLEMATIC LINE
PS .:我不是在寻找替代解决方案(例如使用智能指针或其他方法)。对不起,我的英语!
代码:
class class1
{
private:
unsigned int s;
double* pointer;
public:
/* Constructors */
class1() { s = 0; pointer = nullptr; }
class1(unsigned int us, double* uarray)
{
pointer = new double[us];
for (unsigned int i = 0; i < us; i++)
pointer[i] = uarray[i];
}
class1(const class1& other)
{
pointer = new double[s];
for (unsigned int i = 0; i < s; i++)
pointer[i] = other.pointer[i];
}
~class1() { if (!s && pointer != nullptr) delete[] pointer; }
public:
/* Operators Overloading */
class1& operator=(const class1& other)
{
s = other.s;
pointer = new double[s];
for (unsigned int i = 0; i < s; i++)
pointer[i] = other.pointer[i];
return *this;
}
};
class class2
{
private:
unsigned int m;
unsigned int n;
class1* pointer;
public:
/* Constructors */
class2(unsigned int un, double* uarray, bool flag = false) : n(un)
{
m = 1;
pointer = new class1(un, uarray);
if (flag) { this->function(); }
}
~class2() { if (!m && !n) delete[] pointer; }
public:
/* Public Methods */
void function()
{
class1* newpointer = new class1[n];
//**... some code (when commented show the same error)**
delete[] pointer; //**PROBLEMATIC LINE**
pointer = newpointer;
}
public:
/*Template Constructor*/
template<unsigned int m, unsigned int n>
class2(unsigned int um, unsigned int un, double(&uarray)[m][n], bool flag = false) : m(um), n(un)
{
pointer = new class1[um];
for (unsigned int i = 0; i < um; i++)
{
class1 object1(un, uarray[i]);
pointer[i] = object1;
}
if (flag) { this->function(); }
}
};
int main()
{
double test3[] = { 1, 2, 3 };
double test4[][3] = { {3, 2, 1}, {6, 5, 4}, {9, 8, 7} };
double test5[][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
class2 m4(3, test3, true); //**NOT OK - VIOLATION OF MEMORY**
class2 m5(3, 3, test4, true); //**OK**
}
class1
的副本构造函数未设置s
成员,但在此处使用其不确定的值:
pointer = new double[s];
导致未定义的行为。使用前,请从s
中设置other.s
。
您的第二个构造函数有相同的问题。
您的class1
的赋值运算符正在泄漏内存,因为它没有delete[]
先前的数组。