简体   繁体   中英

Is passing a variable by reference to a function makes the function inline

Background

Reference does not have any memory allocation, it is just another name of the variable. If we pass a variable by reference, it is not stored on the callee function stack (to avoid breaking the "A reference is just an alias" concept). So compiler should copy the callee function body into the caller function itself (I named it making function inline for understanding).

However inline functions have its own rules to consider a function inline.

I completely understand that compiler must play an important role here. It should convert references to pointers on compilation depending on the complexity. I would like to understand the rules generally compiler applies in these cases.

Case 1:

void func(const int& a)
{
    // hudge processing, at least 500 lines of
    // code including loops
    // Will it becomes inline
}

Case 2:

void func(const Person& p)
{
    // Person is a user defined type
    // Person is large class has stl containers
    // hudge processing, at least 500 lines of
    // code including loops
    // Will it becomes inline?
}

Case 3:

void func(const Machine& d)
{
    // Machine is a user defined type
    // func call func recursively multiple times
    // If it becomes inline then it will increase the binary size
}

No. A compiler will not inline the function just because arguments are references.

Technically, references and pointers are strictly the same thing: a memory address pointing to some object. C++ syntax distinguish between references and pointers, but the compiler considers the two concepts as equivalent and will generate the same code whether you pass a variable by reference or by pointer to a function.

In case 1 you are passing a const int& argument to func . While this is perfectly allowed, it typically doesn't make sense since it is cheaper to copy a int variable (normally 4 bytes), than to pass the address of it (8 bytes on 64-bit platform). The called function will need to dereference the address to obtain the value, and this can also prevent some optimizations. It is recommended to pass by reference only variables that are costly to copy.

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