問題
使用traits接收來自中間件的變量,調用拷貝構造函數時提示use of deleted function
錯誤。
解釋
仔細檢查對應類中定義了移動構造函數,而沒有顯式定義拷貝構造函數。而問題就出在這:
If the class definition does not explicitly declare a copy constructor, one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted.
深究
聲明移動構造函數證明你的類需要深拷貝,對於包含指針的類,編譯器簡單的淺拷貝可能導致反復釋放或野指針問題。推廣至Copy constructor 、Move constructor 、Copy assignment operator 、Move assignment operator 、Destructor 這五個函數,定義了任何一個都會導致編譯器認為你在主動管理資源,原本默認生成的函數可能無法滿足需求甚至是錯誤的故被轉換為delete強制用戶手動實現,也就是rule of five規則。
一圖勝千言