简体   繁体   中英

Pass in vs assign const reference in C++

const string& x = functionA();

functionB(x); // depends on x is string or const string&
string str = x;

We have const ref x:

  1. Pass into functionB, so basically we make a copy of the value of x and pass into functionB? (No, depends on x is reference or not)

  2. Assign x to str, so here we also make a copy of value of x? Or we just assign the reference?

=======================

Yeah I understand for functionB(x), it'll depend on if passed-in x is string or string&. My confusion now is still the second one about assignment.

And if we have sth like:

obj.fieldA = x;

obj has been created and we just assign x to the fieldA of obj. Then here x is the copy or just reference?

  1. Calling 'functionB' with 'x' we are just passing that value, which this reference holds.
    By the way, references behave closely to pointers. It's similar to have:
    void func(int val);

    int a = 11;
    int *ptr = &a;
    func(*ptr); // same as functionB(x);

So whether you will pass it by copy or not is really depends on formal parameter of functionB;

  1. Here we have similar circumstances.
    In this line:
    string str = x;
    you are initializing(creating) string 'str' by passing value, which reference 'x' holds, to it's constructor(don't confuse with assignment, because str is being created at this line), and since we have separation of constructors due to move semantics, here you will pass 'x' to 'str's constructor by const reference to make copy of it.

Update:
This obj.fieldA = x; means that you have already created, say, Object obj;
According to this, statement obj.fieldA = x; will be just copying of 'x'.
Maybe I don't understand your last question, but assume that fieldA is again 'string' type;
Then, when you write obj.fieldA = x; , there will be called something like(very bad example, just to simplify):

string& operator=(const string& other){
    ..
    this->str_pointer = new char[other.size() + 1];
    strcpy(this->str_pointer, other.str_pointer);
    ..
} 


and it means that this function took the address of 'x' and copied it's data.
To sum up:

string first = "text";
const string& x = first; // x behaves just like a pointer and holds address of 'first'
Object obj;
obj.fieldA = x; // <--- here

At line I marked due to declaration of 'operator=' which receiving reference(address) you will just pass the address of 'x', and then 'operator=' will look at this memory address and make a copy of data, laying there.
So, we are just assigning the value of 'x' to.fieldA, not the reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM