-1

What does this mean "string ret(v);" in the code below?

char t(char c)
{
    return tolower(c);
}
string toLower(const string & v)
{
    string ret(v);
    transform(ret.begin(), ret.end(), ret.begin(),  t);
    return ret;
}
Fatima
  • 11
  • 2
  • 2
    Creates a new string named `ret` as a copy of `v`. – Aconcagua Mar 25 '19 at 10:10
  • 3
    Would have been preferable to accept the string by value, though; this can avoid unnecessary copies in some cases. – Aconcagua Mar 25 '19 at 10:12
  • 3
    Check out [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Mar 25 '19 at 10:14
  • Read [copy-constructor](https://en.cppreference.com/w/cpp/language/copy_constructor) or [basic_string](https://en.cppreference.com/w/cpp/string/basic_string/basic_string) – Thomas Sablik Mar 25 '19 at 11:56

1 Answers1

0

What does this mean string ret(v); [...]?

This creates a copy of the function argument v with the name ret. This copy is then altered by the call to std::transform and returned by value.

Note that v is passed as a const-qualified reference. It can't be changed within the function. That's why a copy is made to create a string object that can be modified an returned to the caller as a result.

lubgr
  • 37,368
  • 3
  • 66
  • 117