new
anddelete
演算子の使用に小さな問題があります。new
すべての演算子が a に対応しなければならない場所をたくさん読みました。delete
私が理解しているように、で作成された変数は、new
でヒットするまで存続しdelete
ます。次のコードを見ていただきたいのですが、これは長いですが簡単です。
#include <iostream>
using namespace std;
int* testFunction1();
int* testFunction2();
int main(){
int* ptr1 = testFunction1();
int* ptr2 = testFunction2();
cout << *ptr1 << endl; // outputs 5
cout << *(ptr1 - 1) << endl; // outputs random int
cout << *ptr2 << endl; // outputs random int
cout << ptr1 << endl; //prints address of b from testFunction1()
cout << ptr1 - 1 << endl; // prints address of a and c from testFunction1()
cout << ptr2 << endl; // prints address of a and c from testFunction1()
cout << endl;
// delete ptr1; won't work
return 0;
}
int* testFunction1(){
int a = 5, b = 10;
int* pointerToInt1 = new int;
pointerToInt1 = &a;
pointerToInt1 = &b;
cout << &a << endl;
cout << &b << endl;
return pointerToInt1;
}
int* testFunction2(){
int c = 5;
int* pointerToInt2 = &c;
cout << &c << endl;
return pointerToInt2;
}
2 つの質問があります。
testFunction1()
で、ポインタを値で返していることがわかりました。しかし、それを修正してポインタへの参照を返す方法がわかりません。これにより、メイン メソッド (またはその他のメソッド) でメモリを解放できます。逆参照したときに 5 が出力されたのはなぜ
*ptr1
ですか?c
つまり、アドレス出力から、 inに割り当てられた値testFunction2()
がそこに格納されていることは明らかですが、なぜそうなったのでしょうか?