Home > Back-end >  Consult a constructor
Consult a constructor

Time:09-18

In c + + Primer in Chinese version 5 on page 237 of the constructor has the following code:
 
Struct Sales_data {
//the new constructor
Sales_data ()=default;
Sales_data (const STD: : string & amp; S) : bookNo (s) {}//why use reference?
Sales_data (const STD: : string & amp; S, unsigned n, double p) ://why 2 and 3 parameters need not refer to? What's the difference?
Units_sold bookNo (s), (n), revenue (p * n) {}
.
}


Why want to do the first three constructor const STD: : string & amp; S to use references, I tried without references can also be, add references and without reference to what's the difference?

CodePudding user response:

& Is the purpose of reference, to avoid duplicate a STD: : string
Const is to limit it read-only

Const string s words or copied again wouldn't it be a waste, since already a read-only why not directly use reference,

CodePudding user response:

reference 1st floor w170280812 response:
& amp; Is the purpose of reference, to avoid duplicate a STD: : string
Const is to limit it read-only

Const string s words or copied again wouldn't it be a waste, since already a read-only why not directly use reference,

That in this case, why don't you write directly STD: : string s? Direct copy will not change the original value, like the second and the third parameter,

CodePudding user response:

refer to the second floor qq_41065261 response:
Quote: refer to 1st floor w170280812 response:

& Is the purpose of reference, to avoid duplicate a STD: : string
Const is to limit it read-only

Const string s words or copied again wouldn't it be a waste, since already a read-only why not directly use reference,

That in this case, why don't you write directly STD: : string s? Direct copy will not change the original value, like the second and the third parameter,

Efficiency, copy a string need more memory space, also need the CPU to operation,,
If the string you much? Such as tens of thousands of characters, then copy, it will make a great application of overhead
So at the time of "complex object as a parameter, generally USES the" reference "or" pointer ", only need to pass in a memory address to go, don't need to copy

You can simply put "reference" as a "safe usage of pointer", although somewhat one-sided, but I think is more easy to understand,,
  • Related