[英]try {} catch(){} c++
我有以下方法:
class MyClass
{
public:
MyClass;
bool method (MyClass &obj);
};
void MyClass::method (MyClass &obj)
{
MyClass *c = new MyClass;
try{
//code
//access another method
return true;
}
catch (std::string s)
{
}
return false;
}
我應該在哪里從MyClass:
刪除指向對象的指針c
MyClass:
return true
之前或return false
之前?
關於什么:
void MyClass::method (MyClass &obj)
{
MyClass c;
try{
//code
//access another method
return true;
}
catch (std::string s)
{
}
return false;
}
沒有new
->不需要delete
。 method
返回時, c
將自動銷毀。 如果您的示例過於簡單化,並且需要使用new
創建c
,那么您應該遵循其他答案以及智能指針建議。
簡單的答案是,您應該使用智能指針來管理內存(智能指針的選擇取決於代碼的其余部分),這將簡化您的代碼。 實際上,您必須在退出上下文的所有代碼路徑中將其delete
,其中包括兩次返回以及可能引發的任何其他異常。
std::auto_ptr<MyClass> c(new MyClass);
您可以在try and catch之外創建一個變量,將其默認設置為false,而不是將true賦值為true。 而不是返回false返回變量。
然后,可以在返回該變量之前刪除實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.