跳至主要内容

Universal Reference

Introduction

  • lvalue: 有name的value
    • E.g. variables, functions
  • rvalue: 沒有name的value
    • E.g. 1, "abc", MyStruct{}
    • Temporary value

Named return value optimization

當function return temporary object或是local object時,compiler (After c++17)可以做優化,直接把return value construct在接收function return value的變數上。

這樣就不會呼叫到 copy/move constructor

Universal reference

  • 在一個template function理,宣告參數 (T&& param)

    • T是一個未被推斷出來的type
  • reference collapsing

    • 當universal reference出現多於兩個以上的&時,推倒結果的方法
    • 若出現四個&,則推斷成rvalue,其餘則推斷成lvalue