Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which is the Memory efficient way to pass the string as argument to a function.?

can any one tell me .Is there any benefit of passing string as func(string& ) instead of func( string).

like image 498
Balamurugan Avatar asked Oct 19 '11 11:10

Balamurugan


People also ask

How do you pass a string as a function argument?

To pass a one dimensional string to a function as an argument we just write the name of the string array variable. In the following example we have a string array variable message and it is passed to the displayString function.

Which can be passed as an argument to a function?

Arguments are passed by value; that is, when a function is called, the parameter receives a copy of the argument's value, not its address. This rule applies to all scalar values, structures, and unions passed as arguments. Modifying a parameter does not modify the corresponding argument passed by the function call.

How do you pass a string to a function in C++?

First, we have the function definition “DisplayString,” where a constant string reference is passed. The constant strings are defined and initialized in the main function as “str1” and “str2”. After that, pass these constant strings to the function “InputString”.

How do you pass a string?

To pass a string by value, the string pointer (the s field of the descriptor) is passed. When manipulating IDL strings: Called code should treat the information in the passed IDL_STRING descriptor and the string itself as read-only, and should not modify these values.


1 Answers

Passing an object by reference means, well, that you're passing the reference by value, instead of passing the object by value, which means that you have to made a copy at function invocation.

However, passing-by-reference introduces a new set of questions which you must be aware of:

  1. does the function modifies or not the passed object? If it does not, you should put in the const modifier
  2. does the function need to modify the object, but not exposing the modifications outside the function boundaries? In that case what you really want is a copy.
  3. does the function stores somewhere/somehow the reference of the passed object? In that case, you have to understand how object ownership is passed and when it's safe to delete it. You may want to use smart pointers to deal with these issues

The point is: just because passing-by-reference makes function invocation cheaper does not means that you must use it in any case.

like image 105
akappa Avatar answered Oct 15 '22 16:10

akappa