有条件的自动变量
Conditional automatic variable
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()"中传递出来。
相关文章:
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 未初始化的变量有什么危险
- 如何使用 soong 命名空间来有条件地编译模块
- 有条件地将默认参数传递给函数(使用"?"运算符)
- 根据模板类型有条件地删除变量
- 有条件地选择带有 decltype() 和三元运算符的类型
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 有条件的打印和计数在 std::map 上有限制
- 如何在 c++ 中有条件地包含标头?
- 如何仅在Qt是用ltcg构建时才有条件地启用ltcg?
- 如何在Visual Studio 2019中有条件地编译c++源文件
- C++可以有条件地向下转换类指针吗
- 根据成员变量的类型是否存在,有条件地定义该变量
- 有条件地定义了C 中的参考变量
- 等待中有条件变量的班级破坏
- 有条件的自动变量
- 我可以有条件地选择分配给哪个变量吗
- 在初始化成员变量期间有条件地处理异常
- 如何有条件地同时多线程和更新变量
- 是否可以基于宏或变量有条件地编译/运行代码