By reference in C ++

I have this piece of code

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

here I define the = operator, but I can’t understand if I get on the reference stack why it should be & in this == &stack and not this == stack and why we return * to return *this and not this well in advance any help

+4
source share
4 answers

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


We use if(this == &stack) only to ensure approval

  s = s; 

can be processed correctly (especially when you need to delete something in an old object). Comparing pointers is true only when both are the same object. Of course, we could compare the meaning

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

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

+9
source

stack is of type Stack& , and this is of type Stack* . You are checking if stack this address is equal.

+2
source

if I get on the link stack why it should be, and in that == & stack

Because this is a pointer (or "address"), and stack is a link (not a pointer): so you need to say &stack (which means "stack address"), so its type matches the type this .

why do we return * in return * this, not this

Because this is a pointer (not a link), but the method is supposed to return a link (not a pointer), so you need to respect it in order to turn the pointer into a link.

0
source

A short answer to two questions.

  • As I understand it, you ask why we use and sign if we get the link as a function parameter (and not abject). Because the reference to abject is not its address. You must use operator & () to get the address of the object.

  • this is a pointer, but you must return the link, so you return * this

0
source

Source: https://habr.com/ru/post/1311203/


All Articles