[英]Allocate and initialize values for structs inside of a function
I want to use a function to allocate and initialize two related struct instances. 我想使用一个函数来分配和初始化两个相关的结构实例。 However I can't get the memory to persist outside of the allocation function.
但是,我无法使内存保留在分配函数之外。 Also, I'd rather do this without memory leaks if at all possible:
另外,如果可能的话,我宁愿这样做而不会出现内存泄漏:
void alloc_init(foo_struct *bar, foo_struct *baz){
//Create some values in here
bar = new foo_struct(created_val1, created_val2);
baz = new foo_struct(created_val3, created_val4);
}
If I check the value of created_val1
in bar
from within alloc_init()
it's totally fine... But once alloc_init
pops off the stack, I'm getting garbage. 如果我从
alloc_init()
中的bar
检查了created_val1
的值,那完全没问题……但是一旦alloc_init
从堆栈中弹出,我就会alloc_init
。 How do I make these kinds of values persist? 我如何使这些价值观持久化?
You need to pass the pointers by reference: 您需要通过引用传递指针:
void alloc_init(foo_struct *& bar, foo_struct *& baz){
//Create some values in here
bar = new foo_struct(created_val1, created_val2);
baz = new foo_struct(created_val3, created_val4);
}
Because you pass your pointers by value, you're allocating memory for copies of the original pointers inside the functions. 因为按值传递指针,所以您正在为函数内的原始指针的副本分配内存。
You can make them static
, which isn't the greatest solution. 您可以将它们设置为
static
,这不是最大的解决方案。 Or you can declare global variables at a higher scope, such as in a more-persistent class or global variable. 或者,您可以在更高范围内声明全局变量,例如在更持久的类或全局变量中声明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.