const string& x = functionA();
functionB(x); // depends on x is string or const string&
string str = x;
We have const ref x:
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)
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?
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;
string str = x;
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.