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...