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
}
这个函数会做我想做的事(我想让它做的事)吗?也就是说,如果参数是空指针,只在堆栈上分配 B 吗?
最佳答案
Will this function do what I think it does?
不,这是未定义的行为,因为 B
超出范围。由于这是未定义的行为,任何事情都可能发生,因此您无法预测结果。您希望将 B
至少保持在与函数调用相同的范围内,因此只需将其移至方法的顶部即可:
void function(typeA* ptr_to_A) {
typeB B; // typeB is a derived class of typeA
if (!ptr_to_A) {
ptr_to_A = &B;
}
do_stuff_to_ptr_to_A(ptr_to_A);
}
但是如果你只想在 ptr_to_A
为 null 时分配一个 typeB
那么你可以这样做:
void function(typeA* ptr_to_A) {
if (!ptr_to_A) {
typeB B; // typeB is a derived class of typeA
do_stuff_to_ptr_to_A(&B);
} else {
do_stuff_to_ptr_to_A(ptr_to_A);
}
}
关于c++ - 条件自动变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12925669/