有条件的自动变量

Conditional automatic variable

本文关键字:变量 有条件      更新时间:2023-10-16
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?

这个功能会做我认为的吗?

否,这是不确定的行为,因为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);
}

但是,如果您只想分配typeB如果ptr_to_A为null,则可以这样做:

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);
  }
}

您在括号内声明typeb的b,这意味着它仅在该条件性静音(即出现范围)内才有效。在if stategent之前声明b。仅当ptr_to_a为null时,B才会被分配。如果您打算将ptr_to_a从函数" function()"中传递出来。