c++のメモリ解放でdeleteについてなのですが以下の提示コードではnew して新しいクラスのメモリを確保してそれをポインタ変数にアドレスを代入すると思うんですがその前に前newしたものを消さないとどの変数もアドレスを指していないので宙ぶらりんな領域として消せないものが出てしまうのではないかと思うのすがこれはdeleteしてただしのでしょうか?
cpp
1#include <iostream> 2//#include "conio.h" 3using namespace std; 4 5class test 6{ 7 int a; 8public: 9 10 test():a(0){ } 11 12 void print() 13 { 14 cout << a << endl; 15 } 16 17 void (test::* tp)() = &test::print; 18 19 void f2(int x) 20 { 21 a = x; 22 } 23 24 virtual void vf() 25 { 26 cout << "仮想関数\n"; 27 } 28 29 void ft() 30 { 31 cout << "test()\n"; 32 } 33 34// virtual void vf2() = 0;//純枠仮想関数 35 36protected: 37 void pf() 38 { 39 cout << "protected\n"; 40 } 41}; 42 43class sample : public test 44{ 45 int a; 46public: 47 48 void fx() 49 { 50 pf(); 51 } 52 53 void fs() 54 { 55 cout << "sample()\n"; 56 } 57 58 sample():a(0) { } 59 60 void vf() 61 { 62 cout << "派生関数\n"; 63 } 64 65 void print() 66 { 67 cout << a<<endl; 68 } 69 70 void f2(int x) 71 { 72 a = x; 73 } 74 75 virtual void vf2() 76 { 77 cout << "純枠仮想関数\n"; 78 } 79 80 81 82}; 83 84 85int main() 86{ 87 88 test *sa = new test(); 89 sa->vf(); 90 //sa->vf2(); 91 sa->f2(3); 92 sa->print(); 93 94 delete sa;//ここです 95 sa = new sample(); 96 sa->ft(); 97 sa->print(); 98 sa->f2(7); 99 100 test* sb = (test*)sa; 101 102 sb->print(); 103 //sb->vf(); 104// sb->vf2(); 105 106 107 108 109 110// int _r = _getch(); 111 return 0; 112}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2019/04/18 08:47
2019/04/18 13:20
退会済みユーザー
2019/04/20 12:46 編集
2019/04/20 13:36
退会済みユーザー
2019/04/20 13:56
2019/04/20 13:59 編集