1
0
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:
月光xia漫步
2024-05-16 21:27:26 +08:00
committed by GitHub
parent 3a976663f2
commit 9b7512bbba

View File

@@ -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,12 +22,15 @@ 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`.
Please note that this example comes with some risks, as it touches undefined behavior. */
Please note that this example comes with some risks, as it touches undefined behavior. */