【问题标题】:C++ recursively passing by parameter memory issueC ++递归传递参数内存问题
【发布时间】:2013-03-21 21:15:25
【问题描述】:

我的代码中有一个名为“schemeList”的对象,如下所示:

class scheme;
class schemeList
{
    friend class scheme;
private:

    scheme * head;
    schemeList * tail;

public:
    schemeList();
    Token addScheme(vector <Token> &toAdd);
    //...other functions
};

我遇到问题的函数是“addScheme”,它应该向头部添加一个方案,或者如果头部已满,则将其添加到尾部(以链表的方式)。这是我到目前为止的功能:

Token schemeList::addScheme(vector<Token>& toAdd)
{
    if (head->retCloseParen() != ')')
    {
        scheme * headCopy = head;       
        Token answer = head->addScheme(toAdd);
        head = headCopy;
        return  answer;
    }
    else
    {
        //deal with tail
        schemeList * arrow = this;

        while (arrow->tail != NULL)
        {
            arrow = arrow->tail;
        }

        tail = new schemeList();

        tail->head= new scheme();
        tail->tail = NULL;

        Token answer = arrow->tail->addScheme(toAdd);
        return answer;
    }
}

这适用于添加第一个方案,但第二个方案会引发错误,显示“未处理的异常...”。我之前遇到过这样的问题,但我通过引用传递变量 toAdd 而不是传递整个对象来修复它。为什么这会引发错误和/或我该如何解决?

为了让事情更清楚,一个方案是:

class scheme
{
    friend class identifierList;

public:
    Token * id;
    char openParen;
    char closeParen;
    identifierList * idList;

    scheme();
    //other functions
};

class identifierList
{
    friend class scheme;
public:
    Token * id;
    identifierList * next;

    identifierList(Token * inId, identifierList * inNext);
};

一个令牌是:

class Token
{
    friend class datalogProgram;

public:
    int lineNumber;
    string type;
    string value;

    Token(string inType, string inValue, int inLineNum);
    //other functions
};

【问题讨论】:

  • 你应该使用std::liststd::vector而不是浪费时间重新发明链表。
  • 显示您的scheme::addScheme 实现。以及获得异常的调用堆栈。

标签: c++ memory-management stack pass-by-reference datalog


【解决方案1】:
  • 没有提供足够的详细信息,尤其是导致异常的代码。你最好调查一下调用堆栈!
  • 您是否正在使用NULL 初始化head 和其他指针变量 - 我没有看到任何构造函数可以这样做。也没有任何检查(只是head-&gt;retCloseParen() != ')' 检查)。
  • 正如 Thomas 在评论中所建议的,您最好使用一些已经为您提供的容器类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 2022-01-07
    相关资源
    最近更新 更多