return pointer to data declared in function

前端 未结 11 1574
南旧
南旧 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:46

    For C++, you can use a smart pointer to enforce the ownership transfer. auto_ptr or boost::shared_ptr are good options.

提交回复
热议问题