Should I return an rvalue reference parameter by rvalue reference?

前端 未结 4 1774
礼貌的吻别
礼貌的吻别 2020-12-12 22:51

I have a function which modifies std::string& lvalue references in-place, returning a reference to the input parameter:

std::string& tra         


        
4条回答
  •  误落风尘
    2020-12-12 23:15

    if your question is pure optimization oriented it's best to not worry about how to pass or return an argument. the compiler is smart enough to strech your code into either pure-reference passing , copy elision, function inlining and even move semantics if it's the fastest method.

    basically, move semantics can benefit you in some esoteric cases. let's say I have a matrix objects that holds double** as a member variable and this pointer points to a two dimenssional array of double. now let's say I have this expression:
    Matrix a = b+c;
    a copy constructor (or assigment operator, in this case) will get the sum of b and c as a temorary, pass it as const reference, re-allocate m*namount of doubles on a inner pointer, then, it will run on a+b sum-array and will copy its values one by one. easy computation shows that it can take up to O(nm) steps (which can be generlized to O(n^2)). move semantics will only re-wire that hidden double** out of the temprary into a inner pointer. it takes O(1).
    now let's think about std::string for a moment: passing it as a reference takes O(1) steps (take the memory addres, pass it , dereference it etc. , this is not linear in any sort). passing it as r-value-reference requires the program to pass it as a reference, re-wire that hidden underlying C-char* which holds the inner buffer, null the original one (or swap between them), copy size and capacity and many more actions. we can see that although we're still in the O(1) zone - there can be actualy MORE steps than simply pass it as a regular reference.

    well, the truth is that I didn't benchmarked it, and the discussion here is purely theoratical. never the less, my first paragraph is still true. we assume many things as developers, but unless we benchmark everything to death - the compiler simply knows better than us in 99% of the time

    taking this argument into acount, I'd say to keep it as a reference-pass and not move semantics since it's backword compatible and much more understood for developers who didn't master C++11 yet.

提交回复
热议问题