Hi,
I have seen in a lot of places code like
int i;
if(someConditionIstrue)
{
Do some operations and calculate the value of i;
i = some calculated value;
}
use i; //Note this value is only used not changed. It should not be changed.
But unfortunately in this case there is no way to guarantee it.
so now if some one comes and does
i = 10;// This is valid
What i was thinking: is there a way to tell that "i" can be set only once?
After that it will be a constant. Something like
const once int i;
if(someConditionIstrue)
{
Do some operations and calculate the value of i;
i = calculated value;
}
use i; //Note this value is only used not changed.
i = 10;// Compiler error
On 03/04/13 09:21, smisra wrote:
> Hi,
> I have seen in a lot of places code like
>
> int i;
> if(someConditionIstrue)
> {
> Do some operations and calculate the value of i;
> i = some calculated value;
> }
>
> use i; //Note this value is only used not changed. It should not be
> changed.
> But unfortunately in this case there is no way to guarantee it.
> so now if some one comes and does
>
> i = 10;// This is valid
>
> What i was thinking: is there a way to tell that "i" can be set only once?
> After that it will be a constant. Something like
>
> const once int i;
> if(someConditionIstrue)
> {
> Do some operations and calculate the value of i;
> i = calculated value;
> }
>
> use i; //Note this value is only used not changed.
> i = 10;// Compiler error
This seems like the kind of thing attributes were designed for.
Shouldn't that lambda have an explicit return type? Even in a wider sense, any initialization complex enough to support using this idiom will use a lambda that doesn't qualify for an automatically-deduced return type. We might see full automatic return type deduction for lambdas in the future, though, so if that happens, I guess this correction will become moot.
From § 5.1.2/4 in the N3485 draft, it states the following, which disallows an automatically deduced return type other than void for any body other than return <expression>;:
I agree. I'm not quite sure why the limitations were set in the first place. There's a similar fix in the return type deduction proposal, which uses the proposal as leverage for lambda return types as well.
const int i = condition ? { compound-expression-resulting-in-int } : 0;
auto compute_i = [&] () { compound-expression-returning-int };
const int = condition ? compute_i() : 0;