Search code examples
c++pointersreferencereinterpret-cast

Returning int, int* and int& from a function


I just wanted to clarify something, imagine we have the function signature:

1) int* X(){}

2) int Y(){}

3) int& Z(){}

I am trying to work out the exhaustive possibilities of types of values I can return for the above. The below show possible implementations for the above function bodies:

1)

int* X(){
    int* b = new int(6);
    return b;
}

2)

int Y(){
    int b = 6;
    return b;
}

or

int Y(){
    int* b = new int(6);
    return *b;
}

EDIT: 2) not good because of memory leak if b isn't deleted.

3)

int& Z(){
    int b = 6;
    return b;
}

EDIT: 3) not good because b will go out of scope once function returns.

Is there anything I have missed out which could be returned from any of the above 3 function signatures? Getting a bit more adventurous, what about:

int* X(){
    int b = 6;
    return reinterpret_cast<b>;
}

and

int X(){
    int* b = new int(6);
    return reinterpret_cast<b>;
}

? (My understanding of reinterpret_cast may be wrong...)


Solution

  • int Y(){
        int* b = new int(6);
        return b*;
    }
    

    This has a syntax error. To dereference b, you would do *b. Nonetheless, this is a very bad implementation because it leaks memory. The dynamically allocated int will never be destroyed.

    int& Z(){
        int b = 6;
        return b;
    }
    

    This is also bad because you are returning a reference to a local variable. The local variable b will be destroyed when the function returns and you'll be left with a reference to a non-existent object.