简体   繁体   中英

Regarding function returning pointer

I want to clarify something about function returning pointer.

I understand pointer concept but in case of returning from function it is confusing me.

I learnt that when we want to return some data from function we write the type of data in return type for example in case of returning int type of data the return type will be int.

so when we want to return an address of some variable from a function we write return data type to be of some pointer type because memory address point to some sort of memory location that's why the return type is of pointer type what I want to clarify is that now this means that data type of addresses in c++ is of pointer type

This how a general factory function works:

class HobNob;
...
HobNob* CreateHobNob()
{
    return new HobNob();
}
...
HobNob* myHobNob = CreateHobNob();

of course in real life we'd never use bare pointers, but the general idea is we need pointers because we don't want to be passing around HobNob s (which may be huge) but handles (pointers) to one created on the heap. We can now also fully control its lifecycle.

A function that returns a pointer looks something like this:

int* foo()
{
    // some code
    return intPointer; // assuming intPointer is of type int*
}

or

int* foo()
{
    // some code
    return new int; // return a newly created integer
}

If your function is supposed to create a new object of a type and return it.

or

int* foo()
{
    int* arr = new int[10]; // create an array dynamically
    // some code
    return arr; // return an array
}

If your function is supposed to return some array.

Obviously, you can change int with any data type you want.

Also, as someone else pointed out it is not good idea to return the address of a local variable to outside of the function, so you would have to define the local variable as a static variable if you want to do that, otherwise it's undefined behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM