[問題] 記憶體釋放的問題
第一次發文,違反版規請指正
剛遇到的問題想不太懂,上來請教
===以下是程式碼===
#include <iostream>
#include <cstdlib>
using namespace std;
class CWin
{
protected:
char id;
public:
CWin(char i='D'):id(i)
{
}
CWin(const CWin& win)
{
id=win.id;
}
};
class CTextWin : public CWin
{
private:
char *text;
public:
CTextWin(char i,char *tx):CWin(i)
{
text= new char[strlen(tx)+1];
strcpy(text,tx);
}
~CTextWin()
{
delete [] text;
}
void show_member()
{
cout << "Window " << id << ": ";
cout << "text = " << text << endl;
}
void set_member(char i,char *tx)
{
id=i;
delete [] text;
text= new char[strlen(tx)+1];
strcpy(text,tx);
}
};
int main(void)
{
CTextWin tx1('A',"Hello C++");
CTextWin tx2(tx1);
tx1.show_member();
tx2.show_member();
cout << "更改tx1物件的成員之後..." << endl;
tx1.set_member('B',"Welcome C++");
tx1.show_member();
tx2.show_member();
system("pause");
return 0;
}
===螢幕上輸出===
Window A: text = Hello C++
Window A: text = Hello C++
更改tx1物件的成員之後...
Window B: text = Welcome C++
Window A: text = Welcome C++
===問題===
main函數執行完tx2.show_member();
tx1.text與tx2.text會指向同一的位址
main函數執行到tx1.set_member('B',"Welcome C++");
會將tx1.text所指向的記憶體空間清除
tx2.text應該還是指著被清空的記憶體空間
為什麼螢幕上第5行會是Window A: text = Welcome C++
謝謝各位
===新想法===
謝謝purpose
main函數執行到tx1.set_member('B',"Welcome C++");
會將tx1.text所指向的記憶體空間清除
新的記憶體空間剛好就是舊的記憶體空間
因此會有第5行輸出Window A: text = Welcome C++
這個想法對嗎?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.137.6.57
推
01/17 14:17, , 1F
01/17 14:17, 1F
→
01/17 14:18, , 2F
01/17 14:18, 2F
→
01/17 14:24, , 3F
01/17 14:24, 3F
※ 編輯: cryptal1987 來自: 220.137.6.57 (01/17 14:31)
※ 編輯: cryptal1987 來自: 220.137.6.57 (01/17 14:32)
推
01/17 14:50, , 4F
01/17 14:50, 4F
→
01/17 14:51, , 5F
01/17 14:51, 5F
→
01/17 17:30, , 6F
01/17 17:30, 6F
→
01/18 15:46, , 7F
01/18 15:46, 7F