Appleshell
Appleshell

Reputation: 7388

Why is this tuple to tuple-of-references (std::tie) conversion valid?

I'm in the process of making a class "std::tie-able". The class serves as a temporary object that fetches values depending on the type it's assigned to.

This is obvious to implement for assignment to a tuple:

// temporary class conversion operator
template<typename... T>
operator std::tuple<T...>() {
    return fetch_values<T...>(); // returns tuple<T...>
}
// usage:
std::tuple<int, int> = get_temporary();

However the class is supposed to be able to be used with std::tie as well.

int a, b;
std::tie(a, b) = get_temporary();

fetch_values expects value type arguments, so the above needs changes since tie results in T... being reference types. To achieve this I've ended up with an additional method for conversion to tuple-of-references:

template<typename... T>
operator std::tuple<T&...>() {
    auto result = fetch_values<T...>(); // returns tuple<T...>
    return result;
}

This does compile and work, but I have a couple of questions:

Example showing the issue

Upvotes: 2

Views: 816

Answers (1)

Jarod42
Jarod42

Reputation: 218333

your both snippets returns dangling pointer.

You should simply return by value:

// temporary class conversion operator
template<typename... T>
operator std::tuple<T...>() const {
    return fetch_values<T...>(); // returns tuple<T...>
}

The conversion with std::tie will work.

Upvotes: 1

Related Questions