void function(typeA* ptr_to_A) {
if (!ptr_to_A) {
typeB B; // typeB is a derived class of typeA
ptr_to_A = &B;
}
do_stuff_to_ptr_to_A(ptr_to_A);
// my hope is that B is still in scope here so that this function will operate on my B object (which is on the stack) which only gets created if ptr_to_A was initially NULL
}
Will this function do what I think it does (what I want it to do)? That is, only allocate B on the stack if the argument was a null pointer?
No, it’s undefined behavior because
Bgoes out of scope. Since this is undefined behavior anything can happen, and therefore you can’t predict the results. You want to keepBin at least the same scope as the function call, so just move it to the top of the method:But if you only want to allocate a
typeBifptr_to_Ais null then you could do this: