473,379 Members | 1,312 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

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::replaceAll(&strMyStr, &valToFind, &strReplaceWith);

void MyUtil::replaceAll(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::replaceAll(strMyStr, valToFind, strReplaceWith);

void MyUtil::replaceAll(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 myTargetToHoldVarSetInFunction;
somefunction(&myTargetToHoldVarSetInFunction, &someStrParam1,
&someStrParam2);

Whereas I prefer this:
string myTargetToHoldVarSetInFunction = somefunction(&someStrParam1,
&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 2505
"Mike Cain" <aa@aa.comwrote 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 myTargetToHoldVarSetInFunction;
somefunction(&myTargetToHoldVarSetInFunction, &someStrParam1,
&someStrParam2);

Whereas I prefer this:
string myTargetToHoldVarSetInFunction = somefunction(&someStrParam1,
&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::replaceAll(&strMyStr, &valToFind, &strReplaceWith);

void MyUtil::replaceAll(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::replaceAll(strMyStr, valToFind, strReplaceWith);

void MyUtil::replaceAll(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::replaceAll( 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 myTargetToHoldVarSetInFunction;
somefunction(&myTargetToHoldVarSetInFunction, &someStrParam1,
&someStrParam2);

Whereas I prefer this:
string myTargetToHoldVarSetInFunction = somefunction(&someStrParam1,
&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 myTargetToHoldVarSetInFunction = somefunction(&someStrParam1,
&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(&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!
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(&someResult);
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(string &, string const &, string const &)
// -- put in main() or other func --
std::string SetThis( "" ); // empty string
std::cout<<"before SetString="<<SetThis<<std::endl;
SetString( SetThis );
std::cout<<"after SetString="<<SetThis<<std::endl;
// -output-
// before SetString=
// after SetString=abcdefgh

SetString2( SetThis );
std::cout<<"after SetString2="<< SetThis <<std::endl;
std::cout<<"SetString2="<< SetString2( SetThis ) <<std::endl;
// -output-
// after SetString2=Abcdefgh.
// SetString2=Abcdefgh.

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_size() =" << SetThis.max_size() << 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_size() =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
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
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...
3
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) {...
39
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...
1
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...
10
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...
20
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...
20
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...
11
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?
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.