C++ Logo

std-proposals

Advanced search

Re: [std-proposals] [PXXXXR0] Add a New Keyword `undecl`

From: David Brown <david.brown_at_[hidden]>
Date: Wed, 10 Dec 2025 09:46:06 +0100
On 10/12/2025 02:45, codusnocturnus via Std-Proposals wrote:
> The only motivation I can discern from the paper is to reuse a name with
> a different type/meaning, which seems to run counter to every coding
> guideline I’ve ever seen.
>
> It really seems like the existing solutions (using a different name,
> like a1 and a2, or an enclosing scope) are better in every way.
>

The paper does not give any motivation at all that I can see.

I can think of a few motivations for this idea, or related ideas.
Whether or not they are good enough reasons for such a proposal is a
different matter. But mostly I'd want the redeclaration to be possible
without using an "undecl" keyword.

1. Copy-and-paste code (redeclaration without undecl) :

 auto value = get_next();
 if (value) do_something1(*value);

 auto value = get_next();
 if (value) do_something2(*value);

 auto value = get_next();
 if (value) do_something3(*value);

Being able to re-declare a variable identifier at the same brace level
can let you write such repetitive code in a clearer and neater fashion -
whether the redeclarations are the same type or a different type.

(A big question here is where the lifetime of the earlier variables
stops and their destructors are called - does the second declaration
shadow the first exactly as though it were in its own braced block, or
does it end the lifetime of the first variable before its own starts?)

2. Explicitly ending the lifetime of a variable and making it unusable:

 auto x = get_x();
 do_something(x);
 undecl x; // x is destructed here
 do_something_else(x); // Compile-time error

 auto x = get_x();
 do_something(std::move(x));
 undecl x; // x is unusable from here on
 do_something_else(x); // Compile-time error

Marking the identifier as explicitly undeclared means you can't
accidentally use it later. Ideally this would be built into std::move
(but I don't see how that could be done).

3. Const-locking identifiers (redeclaration without undecl) :

It would sometimes be very nice to be able to redeclare a non-const
variable as const, to "lock" it against accidental changes:

 auto x = get_x();
 change_x(&x);
 const auto x = x;
 change_x(&x); // Compile-time error


I know these are not part of the scope of the original proposal, but if
"undecl" is intended to allow the re-use of identifiers at the same
scope, then it could be good to think about what else might be possible
and useful along the same lines.

Received on 2025-12-10 08:46:14