I have the following pseudocode:
function1()//Gets called on startup
{
myclass* obj;
function2(obj);
obj->doSomething();//crashes here!
}
function2(myclass*& ret)
{
myclass* nobj = &myclass();
nobj->doSomething();//Does not crash
ret = &nobj;
}
It would appear that even though I am setting ret to point to nobj, when I try to operate on obj (which should be pointing to nobj, as ret is a reference to obj), my program crashes! Clearly I am doing something wrong, anyone know what it is?
You are taking the address of a temporary by doing &myclass(), which is a no-no because the temporary is destroyed at the end of the expression, and your compiler shouldn't allow it.
Although your compiler is nonconformant in that area already, you are going on to use a destructed object, which is undefined behaviour and is why your code crashes.
Also, I'm not sure how you are assigning a pointer to a pointer to a myclass (&nobj) to a pointer to a myclass (ret). It shouldn't compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With