Passing non-const references to rvalues in C++

前端 未结 7 991
长发绾君心
长发绾君心 2020-12-09 18:28

In the following line of code:

bootrec_reset(File(path, size, off), blksize);

Calling a function with prototype:

static void b         


        
7条回答
  •  粉色の甜心
    2020-12-09 18:53

    Yes, the fact that plain functions cannot bind non-const references to temporaries -- but methods can -- has always bugged me. TTBOMK the rationale goes something like this (sourced from this comp.lang.c++.moderated thread):

    Suppose you have:

     void inc( long &x ) { ++x; }
    
     void test() {
         int y = 0;
         inc( y );
         std::cout << y;
     } 
    

    If you allowed the long &x parameter of inc() to bind to a temporary long copy made from y, this code obviously wouldn't do what you expect -- the compiler would just silently produce code that leaves y unchanged. Apparently this was a common source of bugs in the early C++ days.

    Had I designed C++, my preference would have been to allow non-const references to bind to temporaries, but to forbid automatic conversions from lvalues to temporaries when binding to references. But who knows, that might well have opened up a different can of worms...

提交回复
热议问题