Passing Etiquette (C ++) parameter const and vs. value

If all functions must have a value with a parameter, see its value, shouldn't you always pass this parameter with a constant reference?

One of my colleagues stated that this does not matter for small types, but I do not agree.

So, is there any advantage to this:

void function(char const& ch){ //<- const ref
    if (ch == 'a'){
        DoSomething(ch);
    }
    return;
}

above this:

void function(char ch){ //<- value
    if (ch == 'a'){
        DoSomething(ch);
    }
    return;
}

They seem the same to me:

#include <iostream>
#include <cstdlib>

int main(){

    char ch;
    char& chref = ch;

    std::cout << sizeof(ch) << std::endl; //1
    std::cout << sizeof(chref) << std::endl; //1

    return EXIT_SUCCESS;
}

But I do not know if this is always the case. I believe that I am right, because he does not create any additional overhead costs and documents it himself. However, I want to ask the community if my reasoning and assumptions are correct?

+3
source share
5 answers

, sizeof(chref) sizeof(ch), : , ( ) . , , . , , , const.

, const, , :

void function(const char ch){ //<- value
    if (ch == 'a'){
        DoSomething(ch);
    }
    return;
}
+2

. (char, int) , . , ( ) - .

, , , , .

+3

, , , ( ). , , . , const ( , ). const /STL- const &.

sizeof , chref ch. sizeof(T) T.

+2

. ABI, sizeof(referenceVariable) sizeof(value).

, , ?

. , , , const. / . , - , .

, ( ). , .

. , const ( ).

, , , . const .

+1

, const ( . ). , , . C-, ( ), "char *" , "char" , .

[EDIT: .]

The bottom line, in my opinion, is that when you pass in larger custom types, and the function you call needs to read the values ​​without modifying them, passing in "type const &" is good practice. As you say, it is self-documenting and helps clarify the roles of the various parts of your internal API.

0
source

All Articles