473,575 Members | 3,439 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 2515
"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
12611
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...
3
14920
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
7623
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
2833
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...
10
3408
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...
20
1889
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
4023
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. ...
11
6138
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
8120
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. ...
0
8281
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...
1
7868
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6515
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...
1
5664
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3778
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...
0
3797
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1382
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1107
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...

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.