r4cppp icon indicating copy to clipboard operation
r4cppp copied to clipboard

`mut` vs `const`, non-const reference to const variable in C++.

Open tsocha opened this issue 2 years ago • 0 comments

In sub-chapter: https://github.com/nrc/r4cppp/blob/master/borrowed.md#mut-vs-const There is a sentence: C++ const-ness applies only to the current use of a value, whereas Rust's immutability applies to all uses of a value. So in C++ if I have a const variable, someone else could have a non-const reference to it and it could change without me knowing.

But my little example in C++ could not be compiled because of const type errors:

    int main() {
    	const int data = 5;
    	int& mut_ref = data;
    	int* mut_data = &data;
    	return 0;
    }

Compilation error(tested on gcc 12.3 and gcc 4.7.1):

<source>: In function 'int main()':
<source>:6:24: error: binding reference of type 'int&' to 'const int' discards qualifiers
    6 |         int& mut_ref = data;
      |                        ^~~~
<source>:7:25: error: invalid conversion from 'const int*' to 'int*' [-fpermissive]
    7 |         int* mut_data = &data;
      |                         ^~~~~
      |                         |
      |                         const int*
Compiler returned: 1

Do I understand it correctly? Can you give an example in C++?

Maybe it's worth to rephrase this sentence? The current one is misleading or not precise enough IMHO.

PS: I found a way to make it insecure in C++:

    #include <iostream>
     
    int main() {
    	const int data = 5;
    	int* mut_data = const_cast<int *>(&data);
     
    	*mut_data = 10;
    	std::cout << data << std::endl;
    	std::cout << *mut_data;
    	return 0;
    }

That way it will compile but it's undefined behavior, the new(10) value will not override the old one(5). In gcc and clang there will be no warning and mut_data will be a new pointer value, probably memory will leak as well. obraz

tsocha avatar Jul 19 '23 15:07 tsocha