c++ - 条件自动变量

标签 c++ memory memory-management callstack

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/

相关文章:

c++ - 通过引用传递 r 值?

c++ - C++23 中 std::string::contains 的时间复杂度是多少?

ruby - 如何处理 Ruby 2.1.2 内存泄漏?

c - mem 比较数组以获取匹配字节数

c# - 如何在 C# 中找到内存被用完的地方?

ios - 在弱指针上调用 getter 并将其传递给方法时保留循环可能性

c++ - Arduino 打开 SD 文件名作为字符串

c++ - 为什么类型推导在(非指针)函数类型上失败

linux - 不一致的内存使用结果

iphone - ARC 和 MRC 之间的区别