我有一個很好的資源管理類。具體來說,讓它成爲一個用於管理FILE *的文件類(處理打開和關閉操作)有條件地使用RAII的最佳方式
當存在資源不需要由我管理的情況下,通常的做法是什麼?是別人的責任?
對於ilustrative目的,我現在有這樣的事情:
int main(int argc, char** argv)
{
File my_file(argv[1]); //I unconditionaly obtain the resource
//...
return 0; //and unconditionally relinquish with the destructor
}
而且要像
int main()
{
if(argc <= 1){
//use stdin that is already available
}else{
//obtain a file from argv[1]
}
//...
if(argc <= 1){
//nothing to do
}else{
//close the file we obtained
}
}
(但不太難看,更健壯,等...)
+1,我在幾個地方用noop析構函數使用共享指針。真的很有用 – totowtwo
如果想避免引用計數開銷,也可以用'unique_ptr'來完成。 – ildjarn
unique_ptr @Ildjarn的缺點是必須將deleter類型指定爲模板參數,因此用於非操作案例的刪除器需要與用於其他案例的刪除器類型相同。 –