gpt4 book ai didi

c++ - 条件自动变量

转载 作者:行者123 更新时间:2023-11-28 07:54:47 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com