Search code examples
c++functionreferencec++14

Member function that can return multiple references? (C++)


I have a member function that needs to return multiple references of char member variables.

class Foo {
public:
    Foo() {// ... constructor }
    
    std::string& func();

private:
    char ch1 = 'a', ch2 = 'b', ch3 = 'c';
};

The code below is something would obviously not fulfill my purpose, because the lifetime of the local variable is limited to the scope of the function call:

std::string& func()
{
    std::string total = "";
    total += this-> a;
    total += this-> b;
    total += this-> b;
    
    return total;
}

I would also prefer not to use the method of allocating memory for the local variable using new, then having to delete it after.

I also would not prefer to add a new member variable to the class that is used in the member function and returned.

First of all, is doing this even possible? If so, how can I achieve this?

Many thanks for help.


Solution

  • You can return a std::tuple of references :

    std::tuple<char&, char&, char&> foo::func()
    {
        return std::tie(ch1, ch2, ch3);
    }
    

    You can also use structured binding to unpack the return value :

    int main()
    {
        foo f;
        auto [a, b, c] = f.func();
        b = 'z';    // Modifies `f.ch2`
    }
    

    Live example : https://godbolt.org/z/eM1h6qaxx


    Edit for C++14 :

    Instead of structured binding, you can use std::get to access one of the return values :

    int main()
    {
        foo f;
        auto result = f.func();
        std::get<1>(result) = 'z';    // Modifies `f.ch2`
    }
    

    C++14 live example : https://godbolt.org/z/jrjsr4K7e