return pointer to data declared in function

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

    In C++, you should use new:

    int *myFunction()
    {
        int blah = 4;
        return new int(blah);
    }

    And to get rid of it, use delete:

    int main(void)
    {
        int *myInt = myFunction();
        // do stuff
        delete myInt;
    }

    Note that I'm invoking the copy constructor for int while using new, so that the value "4" is copied onto the heap memory. The only way to get a pointer to something on the stack reliably is to copy it onto the heap by invoking new properly.

    EDIT: As noted in another answer, you will also need to document that the pointer needs to be freed by the caller later on. Otherwise you might have a memory leak.

提交回复
热议问题