开发者

C++ pointer assignment statement doesn't seem to work / do anything

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

inline int search(QueueEntry<T> *current,QueueEntry<T> *previous, unsi开发者_如何学运维gned 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;    
}


The assignment is optimized away by the compiler because it doesn't have any effect on the function's behavior. You reassign previous every time through the loop, but do nothing else with it.

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


Where are you inspecting the value of previous? If you're doing it within this function, after the assignment, then make sure the build has optimizations turned off, and then try it again.

On the other hand, if you're watching previous outside the scope of this function, then it'll never get modified. When you call search() a copy of pointer previous gets loaded onto the stack and you're modifying this copy. The modification disappears after the function exits. To keep the modification around do something like this:

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

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

Or, you can pass a reference and the rest of your code remains the same.

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


You never use your previous variable, therefore, especially if you're compiling with gcc -O2, it's considered a loop invariant, and is optimized away.


Try turning all your optimizations off.

It is likely that the compiler is noticing that that previous=current isn't necessary to do and is simply compiling it out

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜