2 Replies - 226 Views - Last Post: 27 May 2019 - 10:29 PM Rate Topic: -----

#1 TonyRymond   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 49
  • Joined: 09-February 19

string issue c++

Posted 27 May 2019 - 05:56 PM

Hi guys!
String in C++ is just an object of class, in C we were using
char *
and all fine with that also over C++ support that.
but what's confusing me, if I'm using string data type as String , in other words using the facility that C++ provide, why while passing string arguments I must write
 Fun(String &argument)
and not just write
 Fun(String argument)
?

I'm really confused about that ! , I'm making an analogy to
String <=> char * , so why I need while calling function by String value to identify the argument of the function that's type String as &argument ?

for example:
void(std:: const String &argument)
{
cout<<argument;
}



Is This A Good Question/Topic? 0
  • +

Replies To: string issue c++

#2 Skydiver   User is online

  • Code herder
  • member icon

Reputation: 6968
  • View blog
  • Posts: 23,684
  • Joined: 05-May 12

Re: string issue c++

Posted 27 May 2019 - 06:30 PM

Recall that C++ is pass by value. If you have
void Fun(string argument)
{
    :
}


a new instance of the string class is created and passed into Fun().

When you use a reference:
void Fun(string & argument)
{
    :
}


the same instance in passed in.

Why is this a big deal, imagine if your string is 32MB big. If a new instance is made, then another 32MB needs to be allocated, and the existing 32MB of data needs to be copied over into the new instance. This will take time because memory allocation is slow.

Since you have a reference, you could technically modify it. In general, you want to be kind and tell your caller that you won't modify it, so you make your function have the signature:
void Fun(const string & argument)
{
    :
}


this prevents you from accidentally modifyng the string, and it also signals to the caller that they can expect their data to stay intact.
Was This Post Helpful? 0
  • +
  • -

#3 Salem_c   User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 2355
  • View blog
  • Posts: 4,474
  • Joined: 30-May 10

Re: string issue c++

Posted 27 May 2019 - 10:29 PM

Yet more cross-posting from the troll/vampire.
https://cboard.cprog...-cplusplus.html
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1