其他答案是很好的建议。但是,如果您可以控制bar
函数,并且需要能够更改指针指向的bar
对象(这可能是您首先使用双指针的原因),那么最简洁的方法是mystruct *
使用以下签名bar
:
void bar(unsigned int val, mystruct * &foo);
它通过引用传递一个指针,因此您可以更改指针指向的对象,而不会牺牲代码的可读性,例如:
int main()
{
mystruct * foo = new mystruct;
bar(42, foo);
}
void bar(unsigned int val, mystruct * &foo)
{
foo->member1 = val;
foo = new mystruct;
}
没有内存泄漏的完整使用场景可能是:
int main()
{
// allocate dynamically a mystruct whose member1 is equal to 1.
mystruct * foo1 = new mystruct;
mystruct * foo2 = foo1;
foo1->member1 = 1;
// pass by reference foo1
bar(42, foo1);
// here, foo1->member1 == 42 and foo2->member1 == 10
// free memory
delete foo1; // the one allocated in bar()
delete foo2; // the one allocated in main()
}
void bar(unsigned int val, mystruct * &foo)
{
// modify the object allocated in main()
foo->member1 = 10;
// allocate dynamically a mystruct, store its address in foo
foo = new mystruct;
foo->member1 = val;
}