2016-01-23 76 views
-1

我對C++比較陌生,想採用現代實踐。我一直在試圖理解的時候,最好sink一個unique_ptr,這裏是一些代碼,我有:什麼時候接收unique_ptr

class SomeClass 
{ 
    ... 

private: 
    unique_ptr<QStaticText> _text; 
} 


{ 
    ... 

    void SomeClass::setText(unique_ptr<QStaticText> newText) 
    { 
     _text = move(newText); 
    } 

    void SomeClass::setText(const QStaticText& newText) 
    { 
     _text = make_unique<QStaticText>(newText); 
    } 

    ... 
} 

我應該更喜歡一個比其他任何一個或另一個?

+1

第二個應該是首選。但是爲什麼你不能直接擁有'QStaticText'成員還有點不清楚。 –

+0

你的例子很糟糕,但總的想法是,當你想要轉移所有權時,你接受或返回'unique_ptr'。當傳輸的資源無法複製(不可複製,昂貴,完整類型未知)時,這一點尤其重要,這也是您的示例如此糟糕的原因。如果您可以複製並分配'QStaticText',請不要使用指針。通常,避免使用'new',儘管它可能與Qt略有不同。 –

+0

閱讀Herb Sutter:智能指針參數:http://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/ –

回答

0

參考QStaticText的界面,目前還不清楚爲什麼你使用指針(智能或其他)。 (我相信panta rei在評論中也註明了這一點。)看看Why Should I Use a Pointer Rather Than the Object Itself

在這種情況下,它可能是最好能有這樣的事情:

class SomeClass 
{ 
    ... 

private: 
    QStaticText _text; 
}; 


template<class Text> 
void SomeClass::setText(const Text &newText) 
{ 
    _text = QStaticText(newText); 
} 

注意以下幾點:

  1. QStaticText只是偶發的變化進行了優化。

  2. 它可以由至少兩種不同類型構造。

很難看出您現在的計劃獲得了什麼。對於每次更新,無論如何你都要創建多個對象,並且你不能重用它們(你將內容移出它們)。

+0

太棒了,所以不同的方法是:class SomeClass { ... private: QString _text; } { ... 空隙SomeClass的::的setText(常量的QString&newText) { _text = QStaticText(newText); } ... } –

+0

@PeterSpencer是;我寫的只是一個略微的泛化,因爲它可以採用'QString'或'QStaticText'。至於你原來的q。去,但 - 我認爲你目前的建議比原來的更好。 –

相關問題