Update code example in C++ roadmap (#5680)

pull/5685/head
月光xia漫步 6 months ago committed by GitHub
parent 3a976663f2
commit 9b7512bbba
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 6
      src/data/roadmaps/cpp/content/109-language-concepts/101-type-casting/101-const-cast.md

@ -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`:
```cpp
#include <cassert>
#include <iostream>
void modifyVariable(int* ptr) {
@ -21,10 +22,13 @@ int main() {
std::cout << "Original value: " << original_value << std::endl;
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;
}
```
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`.

Loading…
Cancel
Save