我將問題縮小到將2個對象(包含指針數據成員)傳遞給一個簡單的void函數。該函數返回乾淨,但當main()嘗試退出時,它不能回收2個對象中的第一個。下面是一段代碼示例,它顯示了這個問題 - 以及打印語句,以顯示對象在構建,傳遞和銷燬時的地址。無法退出,因爲析構函數錯誤導致執行main()在退出時暫停
如果我只打電話給「print1」 - 程序運行良好。但是,如果我調用「printboth」 - 那麼不能釋放對象「myNumbers」。我也可以通過刪除析構語句使錯誤消失:
delete [] number;
但我不認爲這是一個好主意。
任何人有任何想法?
class dummy
{
public:
dummy() {
number = new int[1];
currentPos = -1;
std::cout<<"default constructor called for "<<this<<std::endl;
}
dummy(int len) {
number = new int[len];
currentPos = -1;
std::cout<<"parameterized constructor called for "<<this<<std::endl;
}
~dummy() {
cout<<"Calling destructor for "<<this<<endl;
delete [] number;
}
int getNextNumber() {
currentPos++;
return number[currentPos];
}
void setNumbers(int position, int value) {
number[position] = value;
}
private:
int* number;
int currentPos;
};
void print1(dummy);
void printboth(dummy, dummy);
int main() {
dummy myNumbers(3);
myNumbers.setNumbers(0,0);
myNumbers.setNumbers(1,1);
dummy myOtherNumbers(3);
myOtherNumbers.setNumbers(0,4);
myOtherNumbers.setNumbers(1,5);
cout<<"Address of myNumbers is "<<&myNumbers<<endl;
cout<<"Address of myOtherNumbers is "<<&myOtherNumbers<<endl;
print1(myNumbers);
printboth(myNumbers, myOtherNumbers);
system("PAUSE");
return 0;
}
void print1(dummy num) {
cout<<"Address of num is "<<&num<<endl;
for (int i=0;i<4;i++)
cout<<"Dummy number1 is "<<num.getNextNumber()<<endl;
return;
}
void printboth(dummy num1, dummy num2) {
cout<<"Address of num1 is "<<&num1<<endl;
cout<<"Address of num2 is "<<&num2<<endl;
for (int i=0;i<4;i++) {
cout<<"Dummy number1 is "<<num1.getNextNumber()<<endl;
cout<<"Dummy number2 is "<<num2.getNextNumber()<<endl;
}
return;
}
你的類不遵循三個規則。使用RAII。 – chris
@chris,將三人和RAII的規則解釋給明確學習的人是有幫助的...... –
好吧,答案有RoT鏈接。這是RAII之一:http://dl.dropbox.com/u/6101039/Modern%20C++.pdf – chris