我對如何正確使用delete關鍵字有點困惑。這是我的情景:C++正確使用刪除後的刪除
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
什麼是錯我的代碼?我的代碼寫得不好嗎?我可以改進它並避免段錯誤嗎?
「Tuple :: Tuple(in columns)」的定義在哪裏?你真的爲'data'分配空間嗎? – suszterpatt
添加構造函數和解構器以提問 –
另外,爲什麼不使用std :: vector而不是數據指針?這將釋放你所有的指針麻煩... – jcxz