473,549 Members | 2,584 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2263
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_su ffix(std::strin g& 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<s td::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_outpu t);


Jul 23 '05 #5


benben schreef:
May I further suggest an alternative:

void foo(vector& input_and_outpu t);


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
29513
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 reference will be handled by the calling function ? Can any one in the group point me to the correct solution for it ? Any code snippets will be of great...
9
11896
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 up to which size m would you expect vector<double> returns_by_value() {
3
1656
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
2119
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 problematic attempt to implement a subscript operator that returns a const reference. The dubious code is marked at the end. <code>
4
2393
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, but allowing iteration through the data? I tryed returning a const vector but the compiler does not like the idea of my using an iterator to look...
26
2786
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 function call. #include <iostream> using namespace std; int* GetArray(); //function prototype void main()
6
2737
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 hostent *hp; int i=0,rc;
3
8801
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 believe that what I have will make a copy of the vector, and my real vector is several hundred bytes. Do I have to cast it as a constant? What is the...
7
2396
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 value occurs in th vector. */
0
7526
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...
0
7457
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7723
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
7965
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...
0
7817
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
3504
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...
1
1949
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
1
1063
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
771
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.