C++ Logo


Advanced search

Re: [std-proposals] Relocation in C++

From: Sebastian Wittmeier <wittmeier_at_[hidden]>
Date: Wed, 18 May 2022 08:54:33 +0200
Thank you. I also read up on Sébastien Bini's section about end of scope.   There are situations, where we would like to end the scope, as the automatic variable or parameter is not needed anymore.   For example:   {     T a;     T2 b(a);     while (flag)         foo(a); // cannot reloc here     // want to end scope of 'a' here, e.g. as 'a' takes lots of resources     bar(b); }   The scopes of 'a' and 'b' are overlapping and we cannot just insert braces.     We could just define an empty function void std::end_scope(auto variable) {}   And call 'std::end_scope(reloc a);' to express intent or just simply 'reloc a;'   at the position, where we want to end the lifetime and scope.     *I would suggest that in those situations - 'reloc a' without using the result - the compiler may just call the destructor and end the scope instead of relocating to a new instance.*   BTW This behavior could also be achieved by the current proposal   bool dummy = false; // always false at runtime if (dummy)     reloc a; // a gets destructed as other code path uses reloc   But we do not want to write preprocessor macros to insert that block.   Best, Sebastian --  Sebastian Wittmeier   -----Ursprüngliche Nachricht----- Von:Edward Catmur <ecatmur_at_[hidden]> Gesendet:Mi 18.05.2022 00:37 Betreff:Re: [std-proposals] Relocation in C++ An:Sebastian Wittmeier <wittmeier_at_[hidden]>; CC:std-proposals_at_[hidden]; On Mon, 16 May 2022 at 08:33, Sebastian Wittmeier <wittmeier_at_[hidden] <mailto:wittmeier_at_[hidden]> > wrote: But with a nonlinear program flow (including simple loops or conditionals), this can get really problematic.   void f() {     string s1, s2, s3;     if (flag)         s2 = reloc s1; // removes s1 from lexical scope     else         s3 = reloc s1; // !!! compilation error } The rule is that if a variable is removed within a substatement of an if statement, and is not explicitly removed within the other substatement, then it is implicitly removed *at the end* of the other substatement (calling its destructor, if appropriate).  As for loops, it is ill-formed to jump over such an expression, in the same way as it is ill-formed to jump over the initialization of an automatic variable; so within a loop you can only reloc automatic variables declared within that loop.

Received on 2022-05-18 06:54:35