C++ Logo

std-proposals

Advanced search

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

From: Sebastian Wittmeier <wittmeier_at_[hidden]>
Date: Sun, 18 Jun 2023 07:03:25 +0200
Again see P2806 do expressions, which allow a 'return expression' from a block.   Otherwise default-construct the variable in the outer block.   Remaining use cases: You have a class, expensive to default-construct, expensive to copy, which you want to extend into an outside block many levels deep.   Use std::optional for delayed construction     Due to the stack region for automatic (local block) variables being destroyed, the scope is not only about C++ language syntax, it is about how the implementation would keep the stack of an inner scope. The variable would have to be saved on the outer scope stack region.   Best, Sebastian   -----Ursprüngliche Nachricht----- Von:Frederick Virchanza Gotham via Std-Proposals <std-proposals_at_[hidden]> Gesendet:So 18.06.2023 00:58 Betreff:[std-proposals] Extend object‘s lifetime beyond closing curly brace An:std-proposals <std-proposals_at_[hidden]>; CC:Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>; #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; } -- Std-Proposals mailing list Std-Proposals_at_[hidden] https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2023-06-18 05:03:27