Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way of returning a pointer

Tags:

c++

I have seen at least 5 C++ tutorial sites that return pointers this way:

int* somefunction(){
    int x = 5;
    int *result = &x;
    return result;
}

Is that not a very, VERY bad idea? My logic tells me that the returned pointer's value can be overwritten at any time. I would rather think that this would be the right solution:

int* somefuntion(){
    int x = 5;
    int* result = new int;
    *(result) = x;
    return result;
}

And then leave the calling function to delete the pointer. Or am i wrong?

like image 765
aggregate1166877 Avatar asked Jun 30 '12 15:06

aggregate1166877


People also ask

How do you return a pointer variable in C++?

So to execute the concept of returning a pointer from function in C/C++ you must define the local variable as a static variable. Example: In the below program, the line of code(int lv = n1 * n1;) will give warning as it is local to the function. To avoid warnings make it static.

How do I return a pointer array?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

How do you return pointers from Functions explain with example?

Return Function Pointer From Function: To return a function pointer from a function, the return type of function should be a pointer to another function. But the compiler doesn't accept such a return type for a function, so we need to define a type that represents that particular function pointer.


1 Answers

Your instinct about the problem is correct- UB is the result. However, your proposed solution is le bad. "Leave the caller to delete it" is hideously error prone and unadvisable. Instead, return it in some owning class that properly encapsulates it's intended usage- preferably std::unique_ptr<int>.

like image 64
Puppy Avatar answered Oct 25 '22 19:10

Puppy