Implicit conversion : const reference vs non-const reference vs non-reference

前端 未结 2 436
春和景丽
春和景丽 2020-12-30 08:07

Consider this code,

struct A {};
struct B {  B(const A&) {} };
void f(B)
{
    cout << \"f()\"<

        
2条回答
  •  遥遥无期
    2020-12-30 08:37

    I would like to hear reasons, rationale and reference(s) from the language specification

    Is The Design and Evolution of C++ sufficient?

    I made one serious mistake, though, by allowing a non-const reference to be initialized by a non-lvalue [comment by me: that wording is imprecise!]. For example:

    void incr(int& rr) { ++rr; }
    
    void g()
    {
        double ss = 1;
        incr(ss);    // note: double passed, int expected
                     // (fixed: error in release 2.0)
    }
    

    Because of the difference in type the int& cannot refer to the double passed so a temporary was generated to hold an int initialized by ss's value. Thus, incr() modified the temporary, and the result wasn't reflected back to the calling function [emphasis mine].

    Think about it: The whole point of call-by-reference is that the client passes things that are changed by the function, and after the function returns, the client must be able to observe the changes.

提交回复
热议问题