C ++ pointer assignment operator doesn't seem to work / does anything

I have the following method in the template class (a simple FIFO queue), and while debugging GDB, I found that the operator reassigning the pointer "previous" to "current" seems to do nothing. the previous ones are started as NULL, and the current one is not NULL when this statement is executed, and the previous one remains as NULL. Has anyone seen anything like this before?

inline int search(QueueEntry<T> *current,QueueEntry<T> *previous, unsigned long long t) { while(current && !(current->getItem()->equals(t))) { previous = current; //**this line doesn't seem to work** current = current->getNext(); } if(current) return 1; return 0; } 
+4
source share
4 answers

Where do you check the value of previous ? If you do this inside this function, after the assignment, make sure the assembly is disabled, and then try again.

On the other hand, if you look at the previous outside the scope of this function, it will never be changed. When you call search() , a copy of the previous pointer is loaded onto the stack, and you modify that copy. Modification disappears after the function exits. To save the changes, do something like this:

 inline int search(QueueEntry<T> *current,QueueEntry<T> **previous, unsigned long long t) { ... *previous = current; ... } 

Now the call to search() will have to pass the address to the pointer instead of the value.

Or you can pass the link, and the rest of your code will remain the same.

 inline int search(QueueEntry<T> *current,QueueEntry<T> *&previous, unsigned long long t) 
+4
source

The assignment is optimized by the compiler because it does not affect the behavior of the function. You reassign the previous every time through the loop, but do nothing with it.

The error, if any, is in the rest of the function.

+6
source

You never use the previous variable, therefore, especially if you compile with gcc -O2 , it is considered a loop invariant and optimized.

+1
source

Try disabling all your optimizations.

The compiler probably notices that previous = current is not needed and just compiles it

0
source

All Articles