我對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);
}
...
}
我應該更喜歡一個比其他任何一個或另一個?
第二個應該是首選。但是爲什麼你不能直接擁有'QStaticText'成員還有點不清楚。 –
你的例子很糟糕,但總的想法是,當你想要轉移所有權時,你接受或返回'unique_ptr'。當傳輸的資源無法複製(不可複製,昂貴,完整類型未知)時,這一點尤其重要,這也是您的示例如此糟糕的原因。如果您可以複製並分配'QStaticText',請不要使用指針。通常,避免使用'new',儘管它可能與Qt略有不同。 –
閱讀Herb Sutter:智能指針參數:http://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/ –