mirror of
https://github.com/kamranahmedse/developer-roadmap.git
synced 2025-08-22 17:02:58 +02:00
Update code example in C++ roadmap (#5680)
This commit is contained in:
@@ -9,6 +9,7 @@ Keep in mind that using `const_cast` to modify a truly `const` variable can lead
|
|||||||
Here's a code example showing how to use `const_cast`:
|
Here's a code example showing how to use `const_cast`:
|
||||||
|
|
||||||
```cpp
|
```cpp
|
||||||
|
#include <cassert>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
void modifyVariable(int* ptr) {
|
void modifyVariable(int* ptr) {
|
||||||
@@ -21,10 +22,13 @@ int main() {
|
|||||||
std::cout << "Original value: " << original_value << std::endl;
|
std::cout << "Original value: " << original_value << std::endl;
|
||||||
|
|
||||||
modifyVariable(non_const_value_ptr);
|
modifyVariable(non_const_value_ptr);
|
||||||
std::cout << "Modified value: " << *non_const_value_ptr << std::endl;
|
std::cout << "Modified value: " << *non_const_value_ptr << ", original_value: " << original_value << std::endl;
|
||||||
|
|
||||||
|
assert(non_const_value_ptr == &original_value);
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
In this example, we first create a `const` variable, `original_value`. Then we use `const_cast` to remove the constness of the variable and assign it to a non-const pointer, `non_const_value_ptr`. The `modifyVariable` function takes an `int*` as an argument and modifies the value pointed to by the pointer, which would not have been possible if we passed the original `const int` directly. Finally, we print the `original_value` and the `*non_const_value_ptr`, which shows that the value has been modified using `const_cast`.
|
In this example, we first create a `const` variable, `original_value`. Then we use `const_cast` to remove the constness of the variable and assign it to a non-const pointer, `non_const_value_ptr`. The `modifyVariable` function takes an `int*` as an argument and modifies the value pointed to by the pointer, which would not have been possible if we passed the original `const int` directly. Finally, we print the `original_value` and the `*non_const_value_ptr`, which shows that the value has been modified using `const_cast`.
|
||||||
|
Reference in New Issue
Block a user