return pointer to data declared in function

前端 未结 11 1599
南旧
南旧 2020-12-17 21:11

I know this won\'T work because the variable x gets destroyed when the function returns:

int* myFunction()
{
    int x = 4; return &x;
}
<
11条回答
  •  爱一瞬间的悲伤
    2020-12-17 21:44

    Boost or TR1 shared pointers are generally the way to go. It avoids the copy overhead, and gives you semi-automatic deletion. So your function should look like:

    boost::shared_ptr myFunction2()
    {
        boost::shared_ptr x = new int; 
    
        *x = 4; 
        return x;
    }
    

    The other option is just to allow a copy. That's not too bad if the object is small (like this one) or you can arrange to create the object in the return statement. The compiler will usually optimize a copy away if the object is created in the return statement.

提交回复
热议问题