From 9b7512bbba73aeb0e5d5c0b2b6d151427cdc40d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=88=E5=85=89xia=E6=BC=AB=E6=AD=A5?= Date: Thu, 16 May 2024 21:27:26 +0800 Subject: [PATCH] Update code example in C++ roadmap (#5680) --- .../101-type-casting/101-const-cast.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/data/roadmaps/cpp/content/109-language-concepts/101-type-casting/101-const-cast.md b/src/data/roadmaps/cpp/content/109-language-concepts/101-type-casting/101-const-cast.md index 732d6d064..8a1e24599 100644 --- a/src/data/roadmaps/cpp/content/109-language-concepts/101-type-casting/101-const-cast.md +++ b/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 #include 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. */ \ No newline at end of file +Please note that this example comes with some risks, as it touches undefined behavior. */