通过函数更深入地传递指针

时间:2012-03-05 05:56:00

标签: c++ pointers parameters

我正在编写一个网络框架(尝试通过UDP实现可靠的层)。我有这个接收函数,接受指向数据包对象的指针。然后,网络框架完成一整套内容以接收数据包,并将数据包指针的值设置为此数据包。但这会发生一些深层次的功能。所以我基本上想知道的是,为什么这对我来说没有这样的工作:(非常基本的例子向你展示我的意思)

void Main()
{
   int* intPointer = NULL;
   SomeFunction(intPointer);
   //intPointer is still null?
}
void SomeFunction(int* outInt)
{
   SomeOtherFunction(outInt);
}

void SomeOtherFunction(int* outInt)
{
   outInt = new int(5);
}

2 个答案:

答案 0 :(得分:5)

SomeOtherFunction按值传递指针,因此赋值仅更改传递地址的本地副本

要使其工作,请通过引用传递指针:

void Main()
{
   int* intPointer = NULL;
   SomeFunction(intPointer);
   //intPointer is still null?
}
void SomeFunction(int*& outInt)
{
   SomeOtherFunction(outInt);
}

void SomeOtherFunction(int*& outInt)
{
   outInt = new int(5);
}

话虽如此,使用返回值是否有问题?

void Main()
{
   int* intPointer = SomeFunction(intPointer);
   //intPointer is still null?
}
int* SomeFunction()
{
   return SomeOtherFunction();
}

int* SomeOtherFunction()
{
   return new int(5);
}

[更新以下评论。 ]

好吧,如果你有一个表示状态的返回值,可能表明是否已经读取了整数,那么你真正想要的是(使用bool作为你特定状态的占位符):

void Main()
{
   int intPointer = 0;
   if (SomeFunction(intPointer) == true)
   {
       // read something
   }
   else
   {
       // failed to read.
   }
}
bool SomeFunction(int& outInt)
{
   return SomeOtherFunction(outInt);
}

bool SomeOtherFunction(int& outInt)
{
   outInt = 5;
   return true;
}

答案 1 :(得分:0)

最好使用空的std :: auto(unique)_ptr作为对SomeOtherFunction和SomeFunction的引用。如果SomeFunction引发异常,则SomeOtherFunction

中分配的内存不会有内存泄漏
相关问题