简体   繁体   中英

Is it ok to return address of rvalue in inline functions?

I know that inline functions get copied into the code each time they are referenced. From my current understanding, I think it would be ok to return the address of an rvalue from an inline function since the function is inside the rest of the code and therefore the rvalue belongs to the scope of the caller function. Is this true?

example:

inline int* addressOfNum(int num){
    return #
} 

int main(){
    int* mynum = addressOfNum(9);
    
    // is the answer "11" or "segmentation fault"?
    int eleven = *mynum + 2;
}

Whether a function is inline has no effect on whether it's ok to return an address of any value.

It can be sometimes ok to return address of an rvalue if it is an xvalue that refers to an object outside the function.

num is not an rvalue expression. Returning an address of a function parameter of object type is never useful. The example function returns an invalid pointer and the behaviour of the program is undefined.

inline does not mean that a function will be inlined. This was always only a hint to the compiler.

Since C++17 this has been codified in the standard and inline now basically just means "multiple definitions are permitted".

Read the details on https://en.cppreference.com/w/cpp/language/inline

And even if the function is inlined it still has to behave as-if it wasn't inlined. Returning the address of an argument is UB, inlined or not.

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