简体   繁体   中英

Operator -> doesn't work as expected in C++

I was practicing single linked list in c++ (practicing how to find the beginning node of the circular list), but found the use of operator -> very confusing. I'm using Visual studio 2010 C++ Express

This works perfectly: head->append(2)->append(3)->append(4)->append(5)

But this doesn't work (to create a circular linked list): head->append(2)->append(3)->append(4)->append(5)->append(head->next)

When I jump in this method and debug, it seems head->next is not passed correctly into the method.

But this works:

  1. Node* tail=head->append(2)->append(3)->append(4)->append(5); tail->append(head->next);
  2. Or after I change return c->next to return head in the two methods, head->append(2)->append(3)->append(4)->append(5)->append(head->next) also works.

What am I missing here? Thank you!

Details of my code is as follows:

void main(){
    Node* head=new Node(1);
    Node* tail=head->append(2)->append(3)->append(4)->append(5)->append(head->next);
    cin.get();
}

class Node{
public:
    Node* next;
    int data;
    bool marked;

    Node(int d){
        data=d;
        marked=false;
        next=NULL;
    }

    Node* append(int d){
        Node* c=this;
        while(c->next!=NULL){
            c=c->next;
        }
        c->next=new Node(d);
        return c->next;
    }

    Node* append(Node* n){
        Node* c=this;
        while(c->next!=NULL){
            c=c->next;
        }
        c->next=n;
        return c->next;
    }
};

You are experiencing undefined behavior .

The problem is that you are expecting head->next to be evaluated at a particular time (right before calling the last append() . But that is not guaranteed.

When you're passing head->next - its before changing it with head->append . I'm afraid you're confusing the order of writing with the order of execution.

In this case you're changing the value and reading it in the same execution statement, that's undefined behavior.

head->next is evaluated first. The compiler is at liberty to do so; see this question .

head-> next在评估语句时为NULL(不指向任何内容)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM