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

前端 未结 5 610
醉梦人生
醉梦人生 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条回答
  •  眼角桃花
    2020-12-04 18:04

    The general rule of thumb for passing by value is when you would end up making a copy anyway. That is to say that rather than doing this:

    void f(const std::vector& x) {
        std::vector y(x);
        // stuff
    }
    

    where you first pass a const-ref and then copy it, you should do this instead:

    void f(std::vector x) {
        // work with x instead
    }
    

    This has been partially true in C++03, and has become more useful with move semantics, as the copy may be replaced by a move in the pass-by-val case when the function is called with an rvalue.

    Otherwise, when all you want to do is read the data, passing by const reference is still the preferred, efficient way.

提交回复
热议问题