Erik de Castro Lopo wrote:

Here's a question for all the C++ crack monkeys. Is it possible
to return an std::string from a function?

Something like:

std::string &
return_string ()
{
    std::string s ;

    // Do something with s.

    return s ;
}

You need to return an actual std::string, not a reference to one (the latter is invalid C++). The normal idiom is to mark the returned string as a const reference in the calling function:

std::string return_string()
{
  std::string s;

  // Do something with s.

  return s;
}

void another_function()
{
  const std::string& returned_string = return_string();
}

Note that you can also use a literal C string in nearly all places where an std::string is required, since there's an auto-converting constructor for an std::string. i.e. You can do this:

std::string return_string()
{
  return "foo";
}


--
% Andre Pang : trust.in.love.to.save  <http://www.algorithm.com.au/>
_______________________________________________
coders mailing list
coders@slug.org.au
http://lists.slug.org.au/listinfo/coders

Reply via email to