@@ -12,39 +12,40 @@ namespace {
1212
1313// const_cast
1414// - const_cast is the only cast that can add/remove const (or volatile)
15- // from a type.
15+ // from a type — nothing else
1616// - main legitimate use: interop with legacy C APIs lacking const correctness
1717// - if you need const_cast a lot — fix the API instead
1818//
1919// Key notes:
20- // - only cast that adds/removes const and volatile — nothing else
2120// - removing const is safe ONLY if original object was not declared const
2221// - modifying a truly const object after const_cast = UB
2322// - prefer mutable over const_cast for class members
2423
2524
2625// // remove const — call legacy C API that isn't const-correct
27- void c_api (char * s ) { // old C API — doesn't modify s but not const
28- printf (" %s" , s );
26+ void c_api (char * ch ) { // old C API — doesn't modify ch but not const
27+ printf (" %s" , ch );
2928}
3029
3130TEST_CASE (" con-cas-1" ) {
3231
3332 const char * msg = " hello" ;
33+ // c_api(const_cast<char*>(msg)); // ✓ safe — c_api doesn't modify it
3434 c_api (const_cast <char *>(msg)); // ✓ safe — c_api doesn't modify it
35+ // remove constness and cast msg to char*
3536
3637
3738 // // remove const — only safe if original object was not const
3839 const int * ptr = new int (42 ); // pointer to const int, !! but underlying
3940 // object is still not const !!
40- int * mp = const_cast <int *>(ptr);
41- *mp = 99 ; // ✓ safe — original object was non-const
41+ int * mut_ptr = const_cast <int *>(ptr);
42+ *mut_ptr = 99 ; // ✓ safe — original object was non-const
4243 REQUIRE (*ptr == 99 );
4344 delete ptr;
4445
4546 const int x = 42 ; // !! underlying object is const !!
46- int * mut_ptr = const_cast <int *>(&x);
47- *mut_ptr = 99 ; // ❌ UB — original object IS const
47+ int * mut_ptr_2 = const_cast <int *>(&x);
48+ *mut_ptr_2 = 99 ; // ❌ UB — original object IS "truly" const
4849 REQUIRE (x == 42 );
4950
5051
@@ -65,8 +66,6 @@ TEST_CASE("con-cas-1") {
6566 }
6667 };
6768
68-
69-
7069}
7170
7271}
0 commit comments