2011-04-01 50 views
3

有沒有辦法將代碼寫入方法的簽名中,無論對象所有權是否更改?在獲取或返回指針的Getter()和Setter()中,您永遠不知道對象所有權是否更改。方法中對象所有權的命名約定

你怎麼看待:

// Uses pConfiguration or creates its own copy - the ownership is un-touched 
void ContainerClass:SetConfiguration(const Configuration* pConfiguration) {} 
// Takes the ownership of pConfiguration (and deletes it in the destructor) 
void ContainerClass:PutConfiguration(Configuration* pConfiguration) {} 
// Returns a 'reference' and keeps the ownership (you must not delete it) 
const Configuration* ContainerClass::GetConfiguration() {} 
// Returns a _new_ object and transfers the ownership to you 
Configuration* ContainerClass::TakeConfiguration() {} 

所以被設置()與PUT()和get()與以()的方式來編碼,或者你可以使用類型(常量與非const) - 或者你是否從上下文知道它?

最好的問候,

查理

+0

你檢查過智能指針嗎?它將避免這些類型的問題。 – Naveen 2011-04-01 07:26:59

+0

嗯......它解決了刪除問題...但它仍然沒有提到對象所有權。我必須考慮 - 如果它解決了我所有的問題:) – Charly 2011-04-01 07:33:06

回答

5

在界面中識別所有權未被更改的最佳方式是不使用指針。首選參考指針:

// Does not take ownership 
void ContainerClass::SetConfiguration(const Configuration& config) {} 

// Does not release ownership 
const Configuration& ContainerClass::getConfiguration() const {} 

當您需要實際轉移內存的所有權時,最好按名稱記錄它。如果你真的覺得渴望,使其在簽名明確,使用好老std::auto_ptr

void ContainerClass::SetConfiguration(std::auto_ptr<Configuration> cfg); 
std::auto_ptr<Configuration> ContainerClass::CopyConfiguration() const; 

std::auto_ptr有奇怪的屬性,複製實際上意味着轉移所有權

2
  1. 編寫良好的文檔和意見(可以使用的doxygen)
  2. 在Qt上,函數經常與打了個比方itemAttakeAtaddXXX總是所有權的方法打轉讓所有權,這反映在文件中。所以你可以使用get()/take()set()/put()。無論如何,好的文檔總是有幫助的,甚至你的功能名稱也是自我解釋的。
+0

是的,良好的文檔是沒有什麼可討論的。但是在簽名中使用命名約定,您可以在代碼中獲得這些信息 - 而不是另一個頭文件。 – Charly 2011-04-01 07:40:54

+0

你不能在同一句話中說* Qt *和*很好的文檔*。 Qt的文檔幾乎沒有,並且功能簽名也沒有(記錄)慣例。 [QBoxLayout :: addWidget](http://doc.qt.io/qt-5/qboxlayout.html#addWidget)是否轉讓其參數的所有權?猜一下。閱讀文檔。閱讀源代碼。請注意,在這一點你嘟* *「wtf!?」*。並停止使用Qt作爲優秀文檔的例子。如果文檔讓你閱讀源代碼,那麼有些東西是非常錯誤的。 – IInspectable 2015-11-10 11:38:21

0

大多數情況下,當使用指針時,沒有「所有權」開始 ,所以沒有任何改變的問題。但設計是關鍵;該類的作用應該明確其與指向的對象 的關係。在比所有權或任何其他更高的水平。而這種關係又決定了它將如何處理對象。

對於所有權相關的特殊情況,std::auto_ptr 是表達轉移的標準方式。這是一個絕對的轉移,但是,儘管如此,如果參數的類型爲std::auto_ptr,則調用者 在他被稱爲函數後甚至不能訪問該對象。 (我 看到這個線程情況下是非常有效的,它有一定道理 對由特定線程擁有的對象,在任何給定時間, 沒有其他線程可以訪問它,並std::auto_ptr表達了這種 很清晰和有效。)