Comportamiento extraño de punteros en c ++
Los siguientes resultados son muy interesantes y tengo dificultades para entenderlos. Básicamente tengo una clase que tiene un int:
class TestClass{
public:
int test;
TestClass() { test = 0; };
TestClass(int _test) { test = _test; };
~TestClass() { /*do nothing*/ };
};
Una función de prueba que acepta un puntero de TestClass
void testFunction1(TestClass *ref){
delete ref;
TestClass *locTest = new TestClass();
ref = locTest;
ref->test = 2;
cout << "test in testFunction1: " << ref->test << endl;
}
Esto es lo que estoy haciendo en main:
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;
}
Esperaba que la salida fuera:
test before: 1
test in testFunction1: 2
test after: 1
Pero me sale la siguiente salida:
test before: 1
test in testFunction1: 2
test after: 2
¿Alguien puede explicar esto? Lo interesante es que cambiando testFunction1 a:
void testFunction1(TestClass *ref){
//delete ref;
TestClass *locTest = new TestClass();
ref = locTest;
ref->test = 2;
cout << "test in testFunction1: " << ref->test << endl;
}
es decir, no elimino la referencia antes de apuntarla a una nueva ubicación, obtengo el siguiente resultado:
test before: 1
test in testFunction1: 2
test after: 1
Realmente apreciaría si alguien me pudiera explicar este extraño comportamiento. Gracias.