try {} catch(){} c ++

sun*_*set 1 c++ try-catch

我有以下方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

我应该在哪里删除之前或之前指向c对象的指针 ?MyClass:return truereturn false

Ste*_*han 10

关于什么:

void MyClass::method (MyClass &obj)
{
    MyClass c;
    try{

        //code 
        //access another method 
        return true;
    }
    catch (std::string s)
    {
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

new- > delete不需要.返回c时自动销毁method.如果你的例子过于简单,你需要创建cnew,你应该遵循与智能指针的建议其他的答案.


Alo*_*ave 9

您应该使用某种形式的RAII,因此您不必费心自己删除该对象.

使用RAII,对象本身负责释放由它获取的资源,而您不必自己完成.

实现RAII的最简单方法之一是使用智能指针.
您可以使用unique_ptr.

  • 我很确定这是OP的中文 (4认同)
  • 当然,在这种情况下,最好只是堆栈分配`MyClass`的实例. (2认同)
  • @yi_H,OP如果是中国人怎么办? (2认同)