Using of rvalue references in c++11

前端 未结 4 1088
渐次进展
渐次进展 2020-12-17 21:18

I would like to implement a function that fills up a vector and then returns an rvalue reference. I tired something like:

std::vector &&fi         


        
4条回答
  •  春和景丽
    2020-12-17 21:50

    For a discussion of rvalue references you can read what Bjarne Stroustrup, the author of C++, has to say about them here:

    http://www2.research.att.com/~bs/C++0xFAQ.html#rval

    Addressing your specific example, the short answer is that due to the Named Return Value Optimization - which is a de facto standard C++ compiler feature even pre-C++11 - if you simply return-by-value the compiler will tie up res and myvec efficiently like you want:

    std::vector fill_list() {
        std::vector res;
        ... do something to fill res ...
        cout << &res << endl; // PRINT POINTER
        return res;
    }
    
    int main(int argc, char **argv) {
         std::vector myvec = fill_list();
         cout << &myvec << endl; // PRINT POINTER
         return 0;
    }
    

    The two "PRINT POINTER" lines will print the same pointer in both cases.

    The vector myvec and the vector res in the above will be the same vector with the same storage. No copy constructor or move constructor will be called. In a sense res and myvec will be two aliases of the same object.

    This is even better than using a move constructor. myvec is constructed and "filled up" in-place.

    The compiler achieves this by compiling the function in an "inplace" mode overlaying an immediate stack position in the callers stack frame with the callees local result variable, and simply leaving it there after the callee returns.

    In this circumstance we say that the constructor has been elided. For more information see here:

    http://en.wikipedia.org/wiki/Return_value_optimization

    In the event that you were assigning the result of fill_list in a non-constructor context, than as a return-by-value results in an xvalue (short for "expiring" value, a type of rvalue), the move assignment operator of the target variable would be given preference if it is available.

提交回复
热议问题