Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::tie — a tuple of references to existing objects

std::tie from <tuple> creates a tuple of lvalue references to existing objects. It lets you assign tuple elements to variables and skip selected positions with std::ignore, without copying the referenced objects.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <tuple>

template<class... TTypes>
constexpr std::tuple<TTypes&...> std::tie(TTypes&... t) noexcept;

std::tie(t...) returns std::tuple<TTypes&...>: a new tuple containing lvalue references to its arguments, not copies of their values. The function is declared constexpr and noexcept and requires <tuple>. Creating the reference tuple alone does not change the arguments.

Assignment to this tuple writes values into the objects referenced by its elements; it does not rebind the references. The expression std::tie(count, std::ignore, score) = std::make_tuple(3, 99, 7) sets count and score, skipping the middle element. Element counts must match, and every nonignored assignment must be valid for the corresponding types. The noexcept on std::tie does not mean subsequent assignments cannot throw exceptions.

With template argument deduction, std::tie(42) is invalid because the deduced int& parameter cannot bind to a temporary. However, std::tie<const int>(42) is valid because the const int& parameter can bind to a temporary. The returned tuple does not extend that temporary’s lifetime past the end of the full-expression containing the call. A const object can be bound, but the resulting reference cannot modify it. The tuple does not own the referenced objects or extend their lifetimes; do not use its references after those objects are destroyed.

Unlike std::tie, std::make_tuple creates value-storing elements for ordinary arguments. In the example, auto refs = std::tie(count, score) still holds references despite using auto. After unpacking the values, writing through std::get<0>(refs) changes count again, so the expected output is 5 7.

Examples

#include <iostream>
#include <tuple>

int main() {
    int count = 0;
    int score = 0;
    auto refs = std::tie(count, score);

    std::tie(count, std::ignore, score) = std::make_tuple(3, 99, 7);
    std::get<0>(refs) = 5;

    std::cout << count << ' ' << score << '\n';
}

Result

5 7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources