Function Overloading Based on Value vs. Const Reference

前端 未结 6 855
借酒劲吻你
借酒劲吻你 2020-11-27 06:21

Does declaring something like the following

void foo(int x)        { std::cout << \"foo(int)\"         << std::endl; }
void foo(const int &x)         


        
6条回答
  •  清酒与你
    2020-11-27 07:13

    The compiler can't. Both definitions of foo can be used for all 'variants' of int.

    In the first foo, a copy of the int is made. Copying an int is always possible.

    In the second foo, a reference to a const int is passed. Since any int can be cast to a const int, a reference to it can be passed as well.

    Since both variants are valid in all cases, the compiler can't choose.

    Things become different if you e.g. use the following definition:

    void foo (int &x);
    

    Now calling it with foo(9) will take the first alternative, since you can't pass 9 as a non-const int reference.

    Another example, if you replace int by a class where the copy constructor is private, then the caller can't make a copy of the value, and the first foo-variant will not be used.

提交回复
热议问题