【发布时间】:2018-05-05 13:09:24
【问题描述】:
我的类有一个问题,似乎只有在我尝试将我的一个对象添加到向量时才会出现。
分配工作正常除非在尝试插入向量时发生(这会在释放内存时导致以下错误:抛出异常:读取访问冲突this->elements 是0xCEDECEDF)。
这是我的赋值运算符和我的复制构造函数。注意elements 是一个int** 指针。
Matrice& Matrice::operator=(const Matrice& other)
{
if (elements)
{
for (size_t i = 0; i < numberoflines; ++i)
if (elements[i])
delete[] elements[i];
delete[] elements;
}
id = other.id;
numberofcols= other.numberofcols;
numberoflines= other.numberoflines;
elements = new int*[numberoflines];
for (size_t i = 0; i < numberoflines; ++i)
elements[i] = new int[numberofcols];
for (size_t i = 0; i < numberoflines; ++i)
for (size_t j = 0; j < numberofcols; ++j)
elements[i][j] = other.elements[i][j];
return *this;
}
Matrice::Matrice(const Matrice& other) {
*this = other;
}
这是Matrice(Matrix) 类的标题:
#pragma once
#include<iostream>
class Matrice {
public:
friend std::istream& operator>>(std::istream&, Matrice&);
friend std::ostream& operator<<(std::ostream&, const Matrice&);
Matrice(const unsigned, const unsigned, const unsigned);
Matrice();
Matrice(const Matrice&);
~Matrice();
Matrice& operator=(const Matrice&);
int operator~()const;
bool operator<(const Matrice&)const;
private:
unsigned id;
unsigned numberoflines;
unsigned numberofcols;
int** elements;
};
下面是构造函数和析构函数:
Matrice::Matrice(unsigned id, unsigned numberoflines, unsigned numberofcols) {
this->id = id;
this->numberoflines = numberoflines;
this->numberofcols = numberofcols;
elements = new int*[numberoflines];
for (size_t i = 0; i < numberoflines; ++i)
elements[i] = new int[numberofcols];
}
Matrice::Matrice() {
numberofcols = 1;
numberoflines = 1;
elements = new int*[numberoflines];
for (size_t i = 0; i < numberoflines; ++i)
elements[i] = new int[numberofcols];
}
Matrice::~Matrice() {
if (elements) {
for (size_t i = 0; i < numberoflines; ++i)
if (elements[i])
delete[] elements[i];
delete[] elements;
}
}
最后我只是在 main 中执行此操作:
std::vector<Matrice> vec;
Matrice obj;
vec.push_back(obj);
【问题讨论】:
-
Matrice类是什么样的? -
所有构造函数都初始化
elements成员吗?在现代 C++ 中,很少有任何好的理由使用new或delete关键字 - 只需使用vector或智能指针即可避免大多数此类问题。 -
我知道这不是最好的方法,但我受到学校的限制,无法使用
new和delete -
它也对我有用。非常感谢。我是这个项目的瓶颈,我讨厌它。但是你有理由解释为什么这可以解决问题吗?
-
您可能希望在赋值运算符的顶部执行
if (this == &other) return *this;,以防止自赋值。