C++ Logo

std-proposals

Advanced search

[std-proposals] Extend object's lifetime beyond closing curly brace

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sat, 17 Jun 2023 23:58:35 +0100
#include <sstream>
#include <iostream>
#include <iomanip>
#include <utility>

int main(int const argc, char **const argv)
{
    {
        std::stringstream ss;
        ss << std::hex << std::setfill('0') << std::setw(8u) << argc;
        std::string result( std::move(ss).str() );
    } -> result;

    std::cout << result << std::endl;
}

In the above code snippet, the closing brace is followed by " ->
result; ". What this means is that the lifetime of the 'result' object
is extended into the outer scope. It would sort of be similar to:

#include <sstream>
#include <iostream>
#include <iomanip>
#include <utility>
#include <optional>

int main(int const argc, char **const argv)
{
    std::optional<std::string> op_result;

    {
        std::stringstream ss;
        ss << std::hex << std::setfill('0') << std::setw(8u) << argc;
        op_result.emplace( std::move(ss).str() );
    }

    std::string &result = op_result.value();

    std::cout << result << std::endl;
}

Received on 2023-06-17 22:58:46