Is returning by rvalue reference more efficient?

后端 未结 2 584
我寻月下人不归
我寻月下人不归 2020-11-22 13:37

for example:

Beta_ab&&
Beta::toAB() const {
    return move(Beta_ab(1, 1));
}
2条回答
  •  天涯浪人
    2020-11-22 14:27

    It can be more efficient, for example, in a bit different context:

    template 
    T&& min_(T&& a, T &&b) {
        return std::move(a < b? a: b);
    }
    
    int main() {
       const std::string s = min_(std::string("A"), std::string("B"));
       fprintf(stderr, "min: %s\n", s.c_str());
       return 0;
    }
    

    As an interesting observation, on my machine clang++ -O3 generates 54 instructions for code above versus 62 instructions for regular std::min. However, with -O0 it generates 518 instructions for code above versus 481 for regular std::min.

提交回复
热议问题