In C++, is it bad to pass a const bool by reference?

前端 未结 6 1665
渐次进展
渐次进展 2021-02-12 23:08

In a practical environment, using gcc or MS Visual Studio, is it bad to pass the value types which are the same size or less than an int by const reference ?

i.e. is it

6条回答
  •  死守一世寂寞
    2021-02-12 23:33

    Performance aside, there are actually cases where you will get different behavior.

    For instance, passing a const reference makes sure that the function cannot change the value of the referenced variable, but another thread might do so. If you pass by reference (even with const), you will see these changes, if you pass by value, you will not.

    Also, the definition of the interface limits what you can do with the variable inside the function. Consider this example:

    int foo(int a) {
        a = 5; // valid
    }
    
    int bar(const int& a) {
        a = 5; // compiler-error
    }
    

    If you pass by reference, and you want to modify the value of the variable for local use, you need to make an extra copy. If you pass by value, you already have a copy.

提交回复
热议问题