【问题标题】:c++ catch catch bad_alloc and delete pointerc++ catch 捕获 bad_alloc 并删除指针
【发布时间】:2013-06-06 18:10:44
【问题描述】:

我有以下功能,我的问题是我无法删除 catch 中的 temp 因为它说 temp 未声明但我不明白为什么?任何帮助表示赞赏。

List_Node*List::copy(const List_Node*  list) 
{
    if(list == nullptr) 
    {
        return nullptr;
    }
    else
    {
        try
        {
            List_Node* temp = new List_Node(list -> value_);
            temp -> next_ = copy(list -> next_);
            return temp;
        }
    catch (bad_alloc& )
    {
      delete temp;   
        throw;
    }
 }

}

【问题讨论】:

  • {} 对中的所有内容都是局部变量。 temptry {} 内部声明,在catch{} 内部不可见。
  • 因为在不同的范围内...
  • 你想删除什么?如果 bad_alloc 已被 new 提出,则分配失败,您没有可删除的内容。
  • 他可能正试图从递归的copy 中捕获bad_alloc,并删除所有之前分配的好指针。

标签: c++ exception pointers


【解决方案1】:

决策可以是这样的:

List_Node*List::copy(const List_Node*  list) 
{
    if(list == nullptr) 
    {
        return nullptr;
    }
    else
    {
        List_Node* temp = 0;
        try
        {
            temp = new List_Node(list -> value_);
            temp -> next_ = copy(list -> next_);
            return temp;
        }
    catch (bad_alloc& )
    {
      delete temp;   
        throw;
    }
 }

}

或者在第一种情况下使用 auto-ptr。

【讨论】:

  • std::auto_ptr 不应使用,请改用std::unique_ptr
  • 我指的是常识中的 auto-ptr(C++98 中的 auto_ptr,C++11 中的 unique_ptr)。
猜你喜欢
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 2010-09-08
  • 1970-01-01
  • 2021-07-30
  • 2011-09-18
  • 2017-04-05
相关资源
最近更新 更多