Aristotle0 Aristotle0 - 26 days ago 10
C++ Question

How to return a reference to an array of ten strings

It's an exercise of C++ Primer 5th. I don't know how to solve it?

The problem described as:

Write the declaration for a function that returns a reference to an array of ten strings, without using either a trailing return, decltype, or a type alias.

My codes:

#include <iostream>
#include <string>

std::string (&func(std::string a[])) [10]
{
return a;
}

int main()
{
std::string a[10];
std::string (&b)[10] = func(a);
for (const auto &c : b)
std::cout << c << std::endl;
return 0;
}


compile errors:


e6_36.cc:6:12: error: non-const lvalue reference to type 'std::string
[10]' cannot bind to a value of unrelated type 'std::string *' (aka
'basic_string, allocator > *')

return a;

^


1 error generated.

Answer Source

You can pass the array by reference, so you can return it :

std::string (&func(std::string (& a) [10])) [10]
{
    return a;
}

Or to make things clearer, use a typedef for your array of strings:

typedef std::string StrArray[10];

StrArray& func2(StrArray& a) {
   return a;
}

EDIT:

When you did :

std::string (&func(std::string a[])) [10]
{
    return a; // error !
}

The argument a is an array of std::string and decays to a pointer to std::string* , which is passed by value (so, copied): You are asking the compiler to bind a non-const reference (the return type) to a temporary, which is illegal in C++.