Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an efficient way to make reference to constants actually const instead of read only?

Let's look at the following C++ code:

#include <iostream>

int main()
{
    int z = 2;

    class A {
        public:
        const int & x;
        A(const int & x) : x(x) {}
        void show(){
            std::cout << "x=" << this->x << std::endl ;
        }
    } a(z);

    a.show();
    z = 3;
    a.show();
}

The program prints: 2 and 3

It clearly shows that while inside class A x can't be modified, it merely means it's read only, because I can change it's value from outside.

Of course I can make it a copy stored inside class A, but I'm wondering if there is (or if there is a proposal?) of a way to say to class A that the member x will be truly constant instead of merely read only, with the meaning of a promise that the external code won't change it ?

To my eyes it looks like something related to the meaning of the C restrict keyword, but I've not heard of any such C++ feature yet. Do you ?

like image 220
kriss Avatar asked Jan 06 '23 22:01

kriss


2 Answers

Constness is an attribute of the actual variable.

The term const int& x simply means "x is a reference to an int which it will not modify" and of course the compiler enforces this.

If you want the actual variable to which x refers to be const, simply declare it so:

#include <iostream>

int main()
{
    const int z = 2;    // declared const. Nothing may ever modify it

    class A {
    public:
        const int & x;
        A(const int & x) : x(x) {}
        void show(){
            std::cout << "x=" << this->x << std::endl ;
        }
    } a(z);

    a.show();
    z = 3;        // this is a logic error, caught by the compiler.
    a.show();
}

compiling correctly produces the error:

./const.cpp:41:7: error: read-only variable is not assignable
    z = 3;
    ~ ^
1 error generated.
like image 149
Richard Hodges Avatar answered Jan 22 '23 20:01

Richard Hodges


You're looking for D's immutable keyword, which was introduced as a new concept in that language precisely because, unfortunately, the answer is no: it does not exist in C++.

like image 37
user541686 Avatar answered Jan 22 '23 21:01

user541686