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

前端 未结 5 608
醉梦人生
醉梦人生 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 17:59

    There is a big difference. You will get a copy of a vector's internal array unless it was about to die.

    int hd(vector a) {
       //...
    }
    hd(func_returning_vector()); // internal array is "stolen" (move constructor is called)
    vector v = {1, 2, 3, 4, 5, 6, 7, 8};
    hd(v); // internal array is copied (copy constructor is called)
    

    C++11 and the introduction of rvalue references changed the rules about returning objects like vectors - now you can do that (without worrying about a guaranteed copy). No basic rules about taking them as argument changed, though - you should still take them by const reference unless you actually need a real copy - take by value then.

提交回复
热议问题