When is a const reference better than pass-by-value in C++11?

前端 未结 5 612
醉梦人生
醉梦人生 2020-12-04 17:13

I have some pre-C++11 code in which I use const references to pass large parameters like vector\'s a lot. An example is as follows:



        
5条回答
  •  Happy的楠姐
    2020-12-04 18:00

    Your example is flawed. C++11 does not give you a move with the code that you have, and a copy would be made.

    However, you can get a move by declaring the function to take an rvalue reference, and then passing one:

    int hd(vector&& a) {
       return a[0];
    }
    
    // ...
    std::vector a = ...
    int x = hd(std::move(a));
    

    That's assuming that you won't be using the variable a in your function again except to destroy it or to assign to it a new value. Here, std::move casts the value to an rvalue reference, allowing the move.

    Const references allow temporaries to be silently created. You can pass in something that is appropriate for an implicit constructor, and a temporary will be created. The classic example is a char array being converted to const std::string& but with std::vector, a std::initializer_list can be converted.

    So:

    int hd(const std::vector&); // Declaration of const reference function
    int x = hd({1,2,3,4});
    

    And of course, you can move the temporary in as well:

    int hd(std::vector&&); // Declaration of rvalue reference function
    int x = hd({1,2,3,4});
    

提交回复
热议问题