Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

by reference in C++

Tags:

c++

I have this snippet of the code

Stack& Stack:: operator=(const Stack& stack){
   if(this == &stack){
      return *this
   }
}

here I define operator = but I can't understand, if I receive by reference stack why it should be & in this == &stack and not this == stack and why we return * in return *this and not this thanks in advance for any help

like image 789
lego69 Avatar asked Dec 23 '22 02:12

lego69


1 Answers

Because this is a pointer (i.e. of type Stack*), not a reference (i.e. not of type Stack&).


We use if(this == &stack) just to ensure the statement

 s = s;

can be handled correctly (especially when you need to delete something in the old object). The pointer comparison is true only when both are the same object. Of course, we could compare by value too

if (*this == stack)
  return *this;
else {
  ...
}

But the == operation can be very slow. For example, if your stack has N items, *this == stack will take N steps. As the assignment itself only takes N steps, this will double the effort for nothing.

like image 97
kennytm Avatar answered Jan 07 '23 06:01

kennytm