2012-03-05 42 views
0

我有一个我正在写的网络框架(试图通过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); 
} 

回答

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; 
} 
+0

分配的内存我的返回值实际上就像ReceiveStatus(并且它会返回ReceiveStatus :: Successful)。所以我不能返回传输状态和同时收到的数据包。无论如何感谢那个男人! – Prodigga 2012-03-05 06:06:05

0

最好使用空的std :: auto(唯一)_ptr作为对SomeOtherFunction和SomeFunction的引用传递。如果SomeFunction引发异常,你将不会有内存泄漏的SomeOtherFunction