mercredi 21 octobre 2020

Using variables by reference

We have Myclass &funcref(); and Myclass func(); and assign the return value to a variable (not a variable reference). If I understand correctly we use the copy constructor in both cases. The only difference is that funcref() returns a reference, and we copy over what is refers to into our object, while in func(), we copy the object while returning.

If we assign it to a variable reference, only func() still needs a copy constructor.

I hope everything until now is correct - if not, please point out my missunderstanding.

Now my question:

It seems like whether we assign the return value of func() to a variable, or a variable reference, it does not change anything at all? Is there any case in which those two will differ? At least when they are assigned, it seems like the process is the same, but I may be wrong.

In code:

class My_class {
    //Anything may be here
};

My_class func();
My_class &funcref();

int main() {
    My_class a = func(); //Copy operator used?
    const My_class &b = func(); //Why does this need to be constant? Also, this uses copy operator, right?
    My_class c = funcref(); //Copy operator used?
    My_class &d = funcref(); //Here, we do not need a copy operator, right?
}

Main question: Except for b being const, is there any difference between a and b? Both seem to be on the stack of main, so do they differ in any way?

Aucun commentaire:

Enregistrer un commentaire