C++ Logo

std-proposals

Advanced search

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

From: Bjorn Reese <breese_at_[hidden]>
Date: Sun, 18 Jun 2023 07:40:52 +0200
On 6/18/23 00:58, Frederick Virchanza Gotham via Std-Proposals wrote:

> 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:

Looks like a use case for immediately invoked lambda

int main(int const argc, char **const argv)
{
     auto result = [&] {
         std::stringstream ss;
         ss << std::hex << std::setfill('0') << std::setw(8u) << argc;
         return ss.str();
     }();

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

Received on 2023-06-18 05:40:55