return pointer to data declared in function

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

    Your second approach is correct. You just need to clearly document that the caller "owns" the result pointer, and is responsible for freeing it.

    Because of this extra complexity, it is rare to do this for "small" types like int, though I'm assuming you just used an int here for the sake of an example.

    Some people will also prefer to take a pointer to an already allocated object as a parameter, rather than allocating the object internally. This makes it clearer that the caller is responsible for deallocating the object (since they allocated it in the first place), but makes the call site a bit more verbose, so it's a trade-off.

提交回复
热议问题