0

newanddelete演算子の使用に小さな問題があります。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 つの質問があります。

  1. testFunction1()で、ポインタを値で返していることがわかりました。しかし、それを修正してポインタへの参照を返す方法がわかりません。これにより、メイン メソッド (またはその他のメソッド) でメモリを解放できます。

  2. 逆参照したときに 5 が出力されたのはなぜ*ptr1ですか? cつまり、アドレス出力から、 inに割り当てられた値testFunction2()がそこに格納されていることは明らかですが、なぜそうなったのでしょうか?

4

2 に答える 2

1

質問を脇に置いて、最初にコードを説明しましょう。

poitnertestFunction1を返すという名前の関数を宣言して定義しますint

int* testFunction1(){
    int a = 5, b = 10;             // define local variables with initial values. a,b have different memory addresses
    int* pointerToInt1 = new int;  // dynamic allocate pointer(new address) to int
    pointerToInt1 = &a;            // set pointerToInt1 to point to address of a
    pointerToInt1 = &b;            // set pointerToInt1 to point to address of b
    cout << &a << endl;           
    cout << &b << endl;
    return pointerToInt1;          // return pointerToInt1 pointer which currently points to address of b
}

a,bfunction 内のローカル変数でありtestFunction1、自動持続時間があり、関数が終了すると解放されるため、pointerToInt1実際にはポインターがぶら下がっていて、未定義の動作にアクセスします。

また、典型的なメモリ リークが で発生しtestFunction1、 によって割り当てられた元のメモリ ブロックnewが失われます。

int* pointerToInt1 = new int;
pointerToInt1 = &a;

"fix"さて、 functionにしましょうtestFunction1、そうです、二重引用符で修正することを意味します。

int* testFunction1(){
    int a = 5, b = 10;             
    int* pointerToInt1 = new int;  
    *pointerToInt1 = a;             // copy a to memory pointerToInt1 
    *pointerToInt1 = b;             // copy b to memory pointerToInt1 
    cout << &a << endl;
    cout << &b << endl;
    return pointerToInt1;           // return pointerToInt1 pointer
}

function を呼び出した後testFunction1でも、動的に割り当てられたメモリ ブロックを削除する必要があります。

int *p = testFunction1();
delete p;

ここで、2 つの質問に戻って復習すると、答えが得られますか?

于 2013-01-27T07:18:33.753 に答える