1

所以我真的很沮丧为什么会这样。我正在实现一个类似于 std::string 的类,但这是使用链接列表而不是数组。我的重载运算符 = 出于某种奇怪的原因无法正常工作。下面你可以看到,当我在方法内打印指针时,字符串被复制到链接列表中,但是当我用这个指针创建一个要返回的字符串对象时,控制台会打印出无限的垃圾。我在这里缺少什么的任何想法?(我只是粘贴相关代码)

static int NumAllocations = 0;

struct ListNode {
    char info;
    ListNode *next;
    ListNode () : info('0'), next(0) {}
    ListNode ( char c ) : info (c), next(0) {}


};


class MyString {
 private:
    ListNode *head;
    static void delstring (ListNode *l);
    static int strlen (ListNode * head);
    static ListNode* strcpy (ListNode *dest, ListNode *src);
 public:

MyString::MyString () : head(0) {}

MyString::MyString (ListNode *l) : head(l) {}

MyString::MyString( const MyString & s ) {
    if (s.head == 0)
        head = 0;
    else
        head = strcpy(head, s.head);
}


MyString MyString::operator = (const MyString & s ){               
    ListNode *renew = NULL;
    if (head != s.head) {
        if (head != 0)
            delstring(this -> head);

        head = strcpy(head, s.head);
        // printList(head); (this prints out the string just fine, so it must be the                                   constructor ? but what about it ?!

        MyString res (head);
        return res;
    }
}


MyString::~MyString(){
    if (head == 0)
        return;
    ListNode *temp = NULL;
    do {
        temp = head -> next;
        delete head;
        -- NumAllocations;
        head = temp;
    } while (temp != 0);
}

静态公共职能

ListNode* MyString::strcpy (ListNode *dest, ListNode *src){
    dest = new ListNode (src -> info);
    ++ NumAllocations;
    ListNode *iter = dest;
    for (ListNode *ptr = src -> next; ptr != 0; ptr = ptr ->next){
        iter -> next = new ListNode (ptr -> info);
        iter = iter -> next;
        ++ NumAllocations;
    }
    return dest;
}


void MyString::delstring (ListNode *l){
    if (l == 0)
        return;
    ListNode *temp = NULL;
    do {
        temp = l -> next;
        delete []l;

        -- NumAllocations;
        l = temp;
    } while (temp != 0);
    l = 0;
}
4

1 回答 1

2

您的赋值运算符有两件事根本上是错误的。

  • 并非所有控制路径都返回值。
  • 首先,您不应该需要临时最终副本。该函数应该返回一个引用,特别是*this

所以...

MyString& MyString::operator = (const MyString & s )
{               
    if (head != s.head) 
    {
        if (head != 0)
            delstring(this -> head);
        head = strcpy(head, s.head);
    }
    return *this;
}

此外,我在这段代码中看到的所有内容都表明ListNode对象是单独分配并链接在一起的,但在delstring成员中你这样做:

void MyString::delstring (ListNode *l)
{
    if (l == 0)
        return;
    ListNode *temp = NULL;
    do {
        temp = l -> next;
        delete []l;  // <<==== vector delete of single allocated item

        -- NumAllocations;
        l = temp;
    } while (temp != 0);
    l = 0;
}

也许试试这个:

void MyString::delstring (ListNode *& l)
{
    while (l)
    {
        ListNode *temp = l;
        l = l->next;
        delete temp;
        --NumAllocations;
    }
}

请注意,这需要指针引用而不是指针。一旦列表为空,它会将调用者的指针设置为 nullptr(假设您在构造时正确终止了列表,并且看起来像您这样做)。

于 2013-10-18T04:45:20.457 回答