473,700 Members | 2,884 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about passing STL strings by reference vs. value

Hi - I am looking for the most efficient way to pass a STL string from one
function to another (using MS VS 7.0 ATL if that matters) and have a few
questions abuot the principles at work here.

Typically I have a helper function that does common things like replace all
occurances of a STL string in a given STL string. These strings can be
quite long in lenght, and therefore I do not want to pass the string by
VALUE because of all the memory allocations etc.

So this is how I currently and pass strings around:

APPROACH 1:

string strMyStr = "whatever foo something foo whatever";
string valToFind = "foo";
string strReplaceWith = "bar";

// replace all occurances of foo with bar
MyUtil::replace All(&strMyStr, &valToFind, &strReplaceWith );

void MyUtil::replace All(string* strMyStr, string* valToFind, string*
strReplaceWith)
{
// reference string values like this: *strMyStr
// call string methods like this: strMyStr->length();
// do replacement, replacing *strMyStr directly with modified
... code goes here, nothing returned
}

APPROACH 2:

string strMyStr = "whatever foo something foo whatever";
string valToFind = "foo";
string strReplaceWith = "bar";

// replace all occurances of foo with bar
MyUtil::replace All(strMyStr, valToFind, strReplaceWith) ;

void MyUtil::replace All(string& strMyStr, string& valToFind, string&
strReplaceWith)
{
// reference string values like this: strMyStr (no preceeding * needed
as in approach 1)
// call string methods like this: strMyStr.length ();
// do replacement, replacing strMyStr directly with modified
... code goes here, nothing returned
}

Can someone please let me know if approach 1 and 2 are identical in terms of
performance and function? Does approach 2 pass by REFERENCE? If so I much
prefer it over approach 1 because of its simplier and cleaner notiation of
just refering to the var without * and ->.

The only downside with either of these techniques is that it makes for
awkward programming syntax because the target variable must be defined ahead
of time. For instance you have to do this with approach 1 or 2:
string myTargetToHoldV arSetInFunction ;
somefunction(&m yTargetToHoldVa rSetInFunction, &someStrPara m1,
&someStrParam2) ;

Whereas I prefer this:
string myTargetToHoldV arSetInFunction = somefunction(&s omeStrParam1,
&someStrParam2) ;

Am I correct, however, with the approach used in that last line of code the
value from the function must be returned by VALUE and therefore a large
string has to be recreated as the function exists and returns a value to the
caller? Any way to use that notation and return by REFERENCE?

Thanks!
Oct 7 '06 #1
5 2517
"Mike Cain" <aa@aa.comwro te in message
news:Hq******** *************** *******@comcast .com...
<snip>
The only downside with either of these techniques is that it makes for
awkward programming syntax because the target variable must be defined
ahead of time. For instance you have to do this with approach 1 or 2:
string myTargetToHoldV arSetInFunction ;
somefunction(&m yTargetToHoldVa rSetInFunction, &someStrPara m1,
&someStrParam2) ;

Whereas I prefer this:
string myTargetToHoldV arSetInFunction = somefunction(&s omeStrParam1,
&someStrParam2) ;

Am I correct, however, with the approach used in that last line of code
the value from the function must be returned by VALUE and therefore a
large string has to be recreated as the function exists and returns a
value to the caller? Any way to use that notation and return by
REFERENCE?

Thanks!
As far as this bit goes, I think it depends on your compiler. Using NRVO
(named return value optimization), I think the compiler's allowed (but not
required) to construct the string directly into the object in the caller
function, i.e. myTarget... in the above.

Trying to find a way to return by reference with things like this is usually
not the right way forward. Local variables no longer exist when the function
exits (so having a reference to them is not a good thing). Trying to keep a
pool of static objects (or similar approaches) fails when you run out of
static objects (i.e. when you call the function one too many times). Other
approaches have similar issues. It's just not a good idea; pass things in by
reference if necessary (i.e. if profiling reveals it to be too slow) but
don't go for anything overly "cunning", which is often a euphemism for
"doesn't always work".

HTH,
Stu
Oct 7 '06 #2
In article <Hq************ *************** ***@comcast.com >,
"Mike Cain" <aa@aa.comwrote :
Hi - I am looking for the most efficient way to pass a STL string from one
function to another (using MS VS 7.0 ATL if that matters) and have a few
questions abuot the principles at work here.

Typically I have a helper function that does common things like replace all
occurances of a STL string in a given STL string. These strings can be
quite long in lenght, and therefore I do not want to pass the string by
VALUE because of all the memory allocations etc.

So this is how I currently and pass strings around:

APPROACH 1:

string strMyStr = "whatever foo something foo whatever";
string valToFind = "foo";
string strReplaceWith = "bar";

// replace all occurances of foo with bar
MyUtil::replace All(&strMyStr, &valToFind, &strReplaceWith );

void MyUtil::replace All(string* strMyStr, string* valToFind, string*
strReplaceWith)
{
// reference string values like this: *strMyStr
// call string methods like this: strMyStr->length();
// do replacement, replacing *strMyStr directly with modified
... code goes here, nothing returned
}

APPROACH 2:

string strMyStr = "whatever foo something foo whatever";
string valToFind = "foo";
string strReplaceWith = "bar";

// replace all occurances of foo with bar
MyUtil::replace All(strMyStr, valToFind, strReplaceWith) ;

void MyUtil::replace All(string& strMyStr, string& valToFind, string&
strReplaceWith)
{
// reference string values like this: strMyStr (no preceeding * needed
as in approach 1)
// call string methods like this: strMyStr.length ();
// do replacement, replacing strMyStr directly with modified
... code goes here, nothing returned
}

Can someone please let me know if approach 1 and 2 are identical in terms of
performance and function?
Yes they are. If I were you though, I would strive to make the function
const correct:

void MyUtil::replace All( string& myStr, const string& valToFind,
const string& replaceWith ) const;
Does approach 2 pass by REFERENCE?
Yes.
The only downside with either of these techniques is that it makes for
awkward programming syntax because the target variable must be defined ahead
of time. For instance you have to do this with approach 1 or 2:
string myTargetToHoldV arSetInFunction ;
somefunction(&m yTargetToHoldVa rSetInFunction, &someStrPara m1,
&someStrParam2) ;

Whereas I prefer this:
string myTargetToHoldV arSetInFunction = somefunction(&s omeStrParam1,
&someStrParam2) ;
In the latter choice, how is the function supposed to know what string
to search in?

--
There are two things that simply cannot be doubted, logic and perception.
Doubt those, and you no longer*have anyone to discuss your doubts with,
nor any ability to discuss them.
Oct 7 '06 #3
>Whereas I prefer this:
> string myTargetToHoldV arSetInFunction = somefunction(&s omeStrParam1,
&someStrParam2 );
Thanks for the quick reply. Glad to hear approach 1 and 2 is identical.
In the latter choice, how is the function supposed to know what string
to search in?
It would be passed as a 3rd param. At a high level I'm trying to figure out
this:

string someResult = somefunction();

Now in somefunction let's say it created a large string. I can't pass this
back by reference because there is no target for that reference right?

Do I understand that the only way to work around this is to use the approach
I described earlier:
string someResult;
somefunction(&s omeResult);

That gets awkward because then I cannot use simple syntax for other things
like passing this return result to another function that takes a string.
For instance I can't do this: some2ndFunction (somefunction() )

I hope my question is making sense but if not please let me know and I will
try to clarify it.

Thanks!
Oct 7 '06 #4
"Mike Cain" <aa@aa.comwrote :
At a high level I'm trying to figure out this:

string someResult = somefunction();

Now in somefunction let's say it created a large string. I can't
pass this back by reference because there is no target for that
reference right?
Correct, but who's to say you need to. RVO may make this a non-issue.
Do I understand that the only way to work around this is to use the
approach I described earlier:

string someResult;
somefunction(&s omeResult);
Or you can use references of course.
That gets awkward because then I cannot use simple syntax for other
things like passing this return result to another function that
takes a string. For instance I can't do this:
some2ndFunction (somefunction() )
You can use the iostream trick:

string& someFunction( string& s ) {
// do whatever to 's' then
return s;
}

Now you could:

string result;
some2ndFunction ( someFunction( result ) );
I hope my question is making sense but if not please let me know and
I will try to clarify it.
Your making sense all right. But you are likely worrying about something
that simply doesn't matter. Just write the function in the most natural
way:

string result = someFunction();

and let the compiler do it's thing. If it turns out to be too slow, then
you can look into changing someFunction as I describe above.

--
There are two things that simply cannot be doubted, logic and perception.
Doubt those, and you no longer*have anyone to discuss your doubts with,
nor any ability to discuss them.
Oct 7 '06 #5

Mike Cain wrote in message ...
>
It would be passed as a 3rd param. At a high level I'm trying to figure out
this:

string someResult = somefunction();

Now in somefunction let's say it created a large string. I can't pass this
back by reference because there is no target for that reference right?

Do I understand that the only way to work around this is to use the approach
I described earlier:
string someResult;
somefunction(& someResult);

That gets awkward because then I cannot use simple syntax for other things
like passing this return result to another function that takes a string.
For instance I can't do this: some2ndFunction (somefunction() )

I hope my question is making sense but if not please let me know and I will
try to clarify it.
Thanks!
????

// include <string>, <iostream>, <ostream>

void SetString(std:: string &text){
text = "abcdefgh";
text += ".";
text.at(0) = 'A';
return;
}
std::string SetString2(std: :string &text){
text = "abcdefgh";
text += ".";
text.at(0) = 'A';
return text;
}

std::string SetString3(std: :string &txt, std::string const &txt2, std::string
const &txt3){
txt = "abcdefgh";
txt += txt2 + txt3;
txt.at(0) = 'A';
return txt;
} // SetString3(stri ng &, string const &, string const &)
// -- put in main() or other func --
std::string SetThis( "" ); // empty string
std::cout<<"bef ore SetString="<<Se tThis<<std::end l;
SetString( SetThis );
std::cout<<"aft er SetString="<<Se tThis<<std::end l;
// -output-
// before SetString=
// after SetString=abcde fgh

SetString2( SetThis );
std::cout<<"aft er SetString2="<< SetThis <<std::endl;
std::cout<<"Set String2="<< SetString2( SetThis ) <<std::endl;
// -output-
// after SetString2=Abcd efgh.
// SetString2=Abcd efgh.

SetThis = "";
std::string S2(" Hello there!");
std::string S3(" How are you today?");
std::string Final = SetString3( SetThis, S2, S3);

std::cout << "SetThis =" << SetThis << std::endl;
// notice that the original string has been modified! (see below)

std::cout << "Final string is =" << Final << std::endl;
// ...and the new string has been assigned to.

SetThis = "";
std::cout << "SetString3 ( SetThis, S2, S3); =" << SetString3( SetThis, S2,
S3) << std::endl;
// ...and SetString3 will work as an arg to another func. accepting a string.

std::cout << "SetThis.max_si ze() =" << SetThis.max_siz e() << std::endl;

// -output-
// SetThis =Abcdefgh Hello there! How are you today?
// Final string is =Abcdefgh Hello there! How are you today?
// SetString3( SetThis, S2, S3); =Abcdefgh Hello there! How are you today?
// SetThis.max_siz e() =1073741820 // [Intel, win98, MinGW]
If that don't 'splain it, tell us *exactly* what you want.

--
Bob R
POVrookie
Oct 7 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
12621
by: harry | last post by:
I have 2 multi-dim arrays double subTotals = null; String rowTitles = null; I want to pass them to a function that initialises & populates them like so - loadData( rowTitles, subTotals);
4
49236
by: Suddn | last post by:
Help me get my mind around passing string types to a function. I need to have the function modify the string types and get them back. Normaly I would just return the modified string but I need to modify about five different strings. I thought that strings were passed by reference in C/C++ but when I pass the strings in they remain unaltered in the calling function. I did test the function being called and they are being althered there.
3
14940
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
39
7647
by: Mike MacSween | last post by:
Just spent a happy 10 mins trying to understand a function I wrote sometime ago. Then remembered that arguments are passed by reference, by default. Does the fact that this slowed me down indicate: a) That I don't know enough b) Passing arguments by ref is bad
1
2838
by: Natalia DeBow | last post by:
Hi, I am working on a Windows-based client-server application. I am involved in the development of the remote client modules. I am using asynchronous delegates to obtain information from remote server and display this info on the UI. From doing some research, I know that the way my implementation works today is not thread-safe, because essentially my worker thread updates the UI, which is BAD. So, here I am trying to figure out how...
10
3429
by: glenn | last post by:
I am use to programming in php and the way session and post vars are past from fields on one page through to the post page automatically where I can get to their values easily to write to a database or continue to process on to the next page. I am now trying to learn ASP to see if we can replace some of our applications that were written in php with an ASP alternative. However, after doing many searches on google and reading a couple...
20
1913
by: David | last post by:
I feel like an idiot asking this but here goes: I understand the 'concept' of scope and passing data by value and/or by reference but I am confused on some specifics. class example{ int i; //my global var private void method1(int myInt){ int x; //local var etc...
20
4037
by: tshad | last post by:
Using VS 2003, I am trying to take a class that I created to create new variable types to handle nulls and track changes to standard variable types. This is for use with database variables. This tells me if a variable has changed, give me the original and current value, and whether the current value and original value is/was null or not. This one works fine but is recreating the same methods over and over for each variable type. ...
11
6162
by: =?Utf-8?B?U3VqZWV0?= | last post by:
If there are long strings (like 1MB or 2MB) is it more performant to pass those by ref to methods or by value?
0
8709
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9202
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9058
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7791
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5894
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4395
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4649
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3081
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2018
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.