Idea/Proposal of Const Statements (aka Freezing)

1,257 views
Skip to first unread message

Andrew Tomazos

unread,
Apr 6, 2019, 11:17:36 PM4/6/19
to std-pr...@isocpp.org
Here is a quick scribble of an idea I've been toying with...

Introduction

We propose const statements.  A const statement makes a variable const.

Minimal Example

int main() {
    int x;
    x = 3; // OK
    std::cout << x; // OK
    const x;
    x = 3; // ERROR: x is const
    std::cout << x; // OK
}

Motivation

It is a common pattern to modify a variable during the first part of a function scope (for example, building out some data structure off to the side) and then intend for it not to be modified for the remainder of the scope (say, looking up the now filled-out data structure).  In such situations, usually programmers simply leave the variable non-const for that remainder, and take the risk of accidental modification - but if a convieniant way was provided to "freeze" a variable it may mitigate this risk.

One might argue that the first part of the function could be factored out into a separate function that returns the variable into a const variable - or, equivalently a new class type created where the modifying part is placed into the constructor.

In practice, often the first part of the function that modifies the variable may not be solely responsible for that side effect, and is folded with other work.  There may be many variables and a complex algorithm in play. In many cases such a factoring would be awkward and unnatural.  As stated previously, we contend that most do not do that, and instead just leave the variable non-const.

Specification

A const statement has the form:

    const N1, N2, ..., Nn;

where each Ni names a variable.  It may only appear at function scope.

Informally, the effect of a const statement is to change the type of each Ni to the const version of its current type for the remainder of the function scope.

Formally, perhaps something like:

    using __T = decltype(N);
    __T* __p = &N;
    const __T& N = (*__p);

With the differences that: __T and __p are exposition only, N may shadow a previous N at the same scope.  N may be a qualified or unqualified name.

Thoughts?

Alberto Barbati

unread,
Apr 8, 2019, 4:40:33 AM4/8/19
to ISO C++ Standard - Future Proposals

Il giorno domenica 7 aprile 2019 05:17:36 UTC+2, Andrew Tomazos ha scritto:
Here is a quick scribble of an idea I've been toying with...

Introduction

We propose const statements.  A const statement makes a variable const.

Thoughts?


Seems a very specific use case for a language feature. Consider that you already have at least two workarounds with lambdas:

const int x = [&]{
   
int x:
   
// code that computes x
   
return x; }();

// x is now const

and

int x;
// code that computes x

[&, x=x]{
   
// x is now const since it's part of closure
}();

Just my two eurocent,
Reply all
Reply to author
Forward
Message has been deleted
0 new messages