我对如何正确使用delete关键字感到困惑。这是我的情景:
class Tuple {
public:
Tuple(int columns);
~Tuple();
void set(int i, string d);
string get(int i);
int columnCount();
private:
string *data;
int columns;
};
Tuple::Tuple(int columns) {
this->columns = columns > 0 ? columns : 0;
if (this->columns > 0) {
data = new string[this->columns];
} else {
data = 0;
}
}
Tuple::~Tuple() {
if (columns > 0) {
delete[] data;
}
}
void Tuple::set(int i, string d) {
if (columns > 0 && i > -1 && i < columns) {
data[i] = d;
}
}
class Table {
public:
Table(int columns);
~Table();
void insertTuple(Tuple t);
Tuple getTuple(int i);
int columnCount();
int rowCount();
private:
vector <Tuple> data;
int columns;
int rows;
};
现在,当我调用以下代码时,我得到一个段错误:
Tuple *outTuple;
outTuple = new Tuple(cCount);
for (int i=0; i<cCount; i++) {
tmpStr = string(reinterpret_cast<const char*>(sqlite3_column_text(statement, i)));
outTuple->set(i, tmpStr);
}
(*outTable)->insertTuple(*outTuple);
delete outTuple; //here I get segfault
我的代码出了什么问题?我的代码写得不好吗?我可以改进它并避免段错误吗?
答案 0 :(得分:3)
最可能的原因是Tuple
违反the rule of three。具体来说,您需要定义复制构造函数和复制赋值运算符。否则,您可能会双重删除data
。
您不显示构造函数和析构函数,但Tuple
使用的内存管理实践看起来很脆弱。为什么不使用std::vector
而不是指针?
答案 1 :(得分:1)
使用指针动态分配内存分配的变量,通常有“容器”或“所有者”。
在这种情况下,该功能是主要的“容器”。
“Containtment”或“Ownership”可能是从功能转移到其他变量,例如,可能是“outTable”。
“outTable”是否从内存中删除了元组?
你打算让“outTable”成为元组的容器,让它从内存中删除元组而不是函数吗?
或者,你打算“outTable”,只引用元组,并让函数从内存中删除元组。
干杯。