Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ reference to pointer

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?

like image 423
Georges Oates Larsen Avatar asked Jan 24 '26 06:01

Georges Oates Larsen


1 Answers

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.

like image 142
Seth Carnegie Avatar answered Jan 25 '26 20:01

Seth Carnegie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!