Date: Sun, 16 Feb 2025 15:23:19 +0100
You can write into the standard that it is UB to cast away const, you cannot fully enforce it at compile-time.
The casting away of const can be done in a function in another translation unit.
It is not nice to have more silent occurences of UB without compile-time warning, which sometimes "work" at runtime, sometimes not.
Of course part of the fault lies with the use of const_cast within UseConstPointer. Why would one ever use const_cast?
The question is, why it would be forbidden here to use const_cast, if it is allowed in other cases. Teachability?
void UseConstPointer(const int* p)
{
int* p2 = const_cast<int*>(p); // sometimes allowed, sometimes forbidden
(*p2)++
}
==================
void UseConstPointer(const int* p);
void foo()
{
int var = init();
.../// do something with var
const var;
UseConstPointer(&var); // indirectly forbidden!
}
void foo()
{
int var = init();
.../// do something with var
const int& var_const = var;
UseConstPointer(&var_const); // allowed!
}
-----Ursprüngliche Nachricht-----
Von:Tiago Freire via Std-Proposals <std-proposals_at_[hidden]>
Gesendet:So 16.02.2025 15:14
Betreff:Re: [std-proposals] Delayed const declaration
An:std-proposals_at_[hidden];
CC:Tiago Freire <tmiguelf_at_[hidden]>; Bo Persson <bo_at_[hidden]>;
It is not allowed to cast away const.
What it means is from that point on (and for the duration of the scope), that variable is const (as if it had been the case all along).
In that case UsePointer(&var);would not be allowed because it would cast away const.
Received on 2025-02-16 14:27:35