簡體   English   中英

嘗試{} catch(){} c ++

[英]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 ,那么您應該遵循其他答案以及智能指針建議。

您應該使用某種形式的RAII ,因此您不必費心刪除自己的對象。

使用RAII,對象本身負責分配它所獲取的資源,而您不必自己做。

實現RAII的最簡單方法之一是使用智能指針
您可以使用unique_ptr

簡單的答案是,您應該使用智能指針來管理內存(智能指針的選擇取決於代碼的其余部分),這將簡化您的代碼。 實際上,您必須在退出上下文的所有代碼路徑中將其delete ,其中包括兩次返回以及可能引發的任何其他異常。

std::auto_ptr<MyClass> c(new MyClass);

您可以在try and catch之外創建一個變量,將其默認設置為false,而不是將true賦值為true。 而不是返回false返回變量。

然后,可以在返回該變量之前刪除實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM