473,382 Members | 1,329 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,382 software developers and data experts.

Returning string or vector from a function

Hi,

What is the recomended way of returning an STL container (e.g.
std::string, std::vector etc fom a function?

Is it by simply returning a local variable? (I doubt it)

std::string foo(const std::string& rhs) {
std::string var = rhs ;
var += " received" ;
return var ;
}

OR by pointer?

std::string *foo(const std::string& rhs) {
std::string *ps = new std::string() ;
*ps = rhs ;
*ps += " received" ; //not sure if this is legal
return ps ;
}
OR by reference ?

std::string &foo(const std::string& rhs) {
std::string var(rhs), &ref ;
var += " received" ;
ref = var ;
return ref ;
}
If anyone would kindly direct me to a web resource where I can readup on
this - I'd be grateful. I have googled for several hours and not really
found anything too useful. even the sgi STL site does not seem to cover
this basic info.

Jul 23 '05 #1
5 2254
Hi

Alfonso Morra wrote:
What is the recomended way of returning an STL container (e.g.
std::string, std::vector etc fom a function?
I don't think there is any...
Is it by simply returning a local variable? (I doubt it)

std::string foo(const std::string& rhs) {
std::string var = rhs ;
var += " received" ;
return var ;
}
Looks reasonable...
OR by pointer?

std::string *foo(const std::string& rhs) {
std::string *ps = new std::string() ;
*ps = rhs ;
*ps += " received" ; //not sure if this is legal (It is) return ps ;
}
I would _never_ return (raw) pointers to newly allocated objects:

1. There can easily be memory leaks:
foo("bar");

2. It is generally a bad idea as the caller does not necessarily know
whether he's required to free the memory, how to free the memory, ...
OR by reference ?

std::string &foo(const std::string& rhs) {
std::string var(rhs), &ref ; ^ A reference needs to be bound... var += " received" ;
ref = var ;
return ref ;
}


What you're planning to do here is quite a bad idea. You effectively want to
return a reference to a non-existent object ('var' has just gone out of
scope...)

You (might) have another option anyway:
std::string& add_received_suffix(std::string& str)
{
str += " received";
return str;
}
Markus

Jul 23 '05 #2
Alfonso Morra wrote:
Hi,

What is the recomended way of returning an STL container (e.g.
std::string, std::vector etc fom a function?

Is it by simply returning a local variable? (I doubt it)

std::string foo(const std::string& rhs) {
std::string var = rhs ;
var += " received" ;
return var ;
}
Returns a copy of the local, which is fine.
OR by pointer?

std::string *foo(const std::string& rhs) {
std::string *ps = new std::string() ;
*ps = rhs ;
*ps += " received" ; //not sure if this is legal
return ps ;
}
// But who deletes the memory poined to by ps?

OR by reference ?

std::string &foo(const std::string& rhs) {
std::string var(rhs), &ref ; // Whats ref? Referecences need to point to something that exists. var += " received" ;
ref = var ;
return ref ;
}
// Did you intend:
std::string &foo(const std::string& rhs) {
std::string var(rhs);
var += " received" ;
return var ;
}

// Return reference to local, which is now out of scope!


If anyone would kindly direct me to a web resource where I can readup on
this - I'd be grateful. I have googled for several hours and not really
found anything too useful. even the sgi STL site does not seem to cover
this basic info.


Try it:
#include <iostream>
#include <string>

std::string cFoo(const std::string& rhs) {
std::string var = rhs ;
var += " received" ;
return var ;
}

std::string *pFoo(const std::string& rhs) {
std::string *ps = new std::string() ;
*ps = rhs ;
*ps += " received" ; //not sure if this is legal
return ps ;
}

std::string &rFoo(const std::string& rhs) {
std::string var(rhs);
var += " received" ;
return var ;
}

int main(int argc, char* argv[])
{
// This works!
std::cout << cFoo("cFoo") << std::endl;
// this next line leaks the memory
std::cout << *pFoo("pFoo") << std::endl;
// This is just wrong!
std::cout << rFoo("rFoo") << std::endl;

return 0;
}

I don;t know how to test the stream state, so I'll leave that up to somebody else.

On my compiler VC 7.1, that last line doesn't output anything, and "breaks" the stream.

Ben
--
I'm not just a number. To many, I'm known as a String...
Jul 23 '05 #3
Alfonso Morra wrote:
Hi,

What is the recomended way of returning an STL container (e.g.
std::string, std::vector etc fom a function?

Is it by simply returning a local variable? (I doubt it)

std::string foo(const std::string& rhs) {
std::string var = rhs ;
var += " received" ;
return var ;
}
The function above is perfectly fine. The only issue may be that the
local variable (var) is copied to the destination which may be a tad
less efficient but I would not let that get in the way of using it
unless you saw a performance issue. I would just write it a little
simpler than this:

std::string foo(const std::string& rhs) {
return rhs + " received";
}


OR by pointer?

std::string *foo(const std::string& rhs) {
std::string *ps = new std::string() ;
*ps = rhs ;
*ps += " received" ; //not sure if this is legal
return ps ;
}
This is OK too but prone to errors. Use a std::auto_ptr to eliminate the
chance of errors.

std::auto_ptr<std::string> foo(const std::string& rhs)


OR by reference ?

std::string &foo(const std::string& rhs) {
std::string var(rhs), &ref ;
var += " received" ;
ref = var ;
return ref ;
}
This is just plain bad. I'm surprised if it compiles.

a) All references must be seated (initialized) when they are created
(ref = var) is meaningless.

b) Returning a reference to a local variable is bad since the object
being referenced will be destroyed before it can be used by the caller.


If anyone would kindly direct me to a web resource where I can readup on
this - I'd be grateful. I have googled for several hours and not really
found anything too useful. even the sgi STL site does not seem to cover
this basic info.


http://www.parashift.com/c++-faq-lite/index.html
Jul 23 '05 #4
May I further suggest an alternative:

void foo(vector& input_and_output);


Jul 23 '05 #5


benben schreef:
May I further suggest an alternative:

void foo(vector& input_and_output);


or

template< typename OutputIterator >
void foo( OutputIterator out );

That way you don't even have to care about whether your caller
wants a vector<char> or a string. Both have back_inserters. Or,
if the caller thinks it's easier, foo could also write to a
stream_iterator.

HTH,
Michiel Salters

Jul 23 '05 #6

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

Similar topics

2
by: tornado | last post by:
hi all, i am pretty new to c++. i have this problem for which i am unable to think a solution. i don't understand how to pass a vector refernce back to the callin function. And how this...
9
by: mjm | last post by:
Folks, Stroustrup indicates that returning by value can be faster than returning by reference but gives no details as to the size of the returned object up to which this holds. My question is...
3
by: replicat | last post by:
How do I do this? I have my function: int* calc_c2e(string it, entry ea) { // .......... and in the end I want to return an integer array. Help is much appreciated :)
18
by: cppaddict | last post by:
Hi, Is it considered bad form to have the subscript operator return a const reference variable? If not, what is the proper way to do it? My question was prompted by the code below, my...
4
by: cpisz | last post by:
At least that is what I think I want to do. What is the proper way for me to return multiple data member objects from an accessor method in my class while ensuring the data does not get changed,...
26
by: cdg | last post by:
Could anyone correct any mistakes in this example program. I am just trying to return an array back to "main" to be printed out. And I am not sure how a "pointer to an array" is returned to the...
6
by: Rahul K | last post by:
Hi I am working on Visual Studio on Windows. I have a function which return the list of all the IP Addresses of a machine: vector<char *getAllLocalIPAddress() { char localHostName; struct...
3
by: Michele | last post by:
Hello: What is the syntax for returning a reference to a vector from a function? I have a private vector and I want to return it using a public get function (like in the code below), but I...
7
by: arnuld | last post by:
/* C++ Primer - 4/e * * 1st example from section 7.2.2, page 234 * returning 2 values from a function * * STATEMENT: * to find a specific value in a vector and number of times * that...
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: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.