Dziwne zachowanie wskaźników w c ++

Następujące wyniki są bardzo interesujące i mam trudności z ich zrozumieniem. Zasadniczo mam klasę, która ma int:

class TestClass{
public:
    int test;
    TestClass() { test = 0; };
    TestClass(int _test) { test = _test; };
    ~TestClass() { /*do nothing*/ };
};

Funkcja testowa, która akceptuje wskaźnik klasy TestClass

void testFunction1(TestClass *ref){
    delete ref;
    TestClass *locTest = new TestClass();
    ref = locTest;
    ref->test = 2;
    cout << "test in testFunction1: " << ref->test << endl;
}

To właśnie robię w głównej mierze:

int main(int argc, _TCHAR* argv[])
{
    TestClass *testObj = new TestClass(1);
    cout << "test before: " << testObj->test << endl;
    testFunction1(testObj);
    cout << "test after: " << testObj->test << endl;
    return 0;
}

Spodziewałem się, że wyjście będzie:

test before: 1
test in testFunction1: 2
test after: 1

Ale otrzymuję następujące dane wyjściowe:

test before: 1
test in testFunction1: 2
test after: 2

Czy ktoś może to wyjaśnić. Interesujące jest to, że zmiana funkcji testFunction1 na:

void testFunction1(TestClass *ref){
    //delete ref;
    TestClass *locTest = new TestClass();
    ref = locTest;
    ref->test = 2;
    cout << "test in testFunction1: " << ref->test << endl;
}

tj. nie usuwam ref przed skierowaniem go do nowej lokalizacji, otrzymuję następujące dane wyjściowe:

test before: 1
test in testFunction1: 2
test after: 1

Naprawdę doceniłbym, gdyby ktoś mógł mi wyjaśnić to dziwne zachowanie. Dzięki.

questionAnswers(6)

yourAnswerToTheQuestion