Last active
April 27, 2023 13:15
-
-
Save tmsampson/124e78bc10436f8ecb772e32f1d70ee7 to your computer and use it in GitHub Desktop.
C++ Const Pointer Usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//------------------------------------------------------------------------------------------------------------------------------ | |
struct MyType | |
{ | |
int x = 0; | |
void Mutate() { ++x; } | |
}; | |
//------------------------------------------------------------------------------------------------------------------------------ | |
int main() | |
{ | |
MyType a, b; | |
// Example #1 - No const usage | |
MyType* example1 = &a; | |
example1 = &b; // OK: Pointer value (address) is mutable | |
example1->Mutate(); // OK: Object is mutable | |
// Example #2 - Pointer value (address) is const, object remains mutable | |
// NOTE: In C#, this is equivalent to using readonly with reference types | |
MyType* const example2 = &a; | |
example2 = &b; // ERROR: Pointer value (address) is const | |
example2->Mutate(); // OK: Object is mutable | |
// Example #3 - Pointer value (address) is mutable, object is const | |
const MyType* example3 = &a; | |
example3 = &b; // OK: Pointer value (address) is mutable | |
example3->Mutate(); // ERROR: Object is const | |
// Example #4 - Pointer value (address) and object are both const | |
// NOTE: In C#, this is equivalent to using readonly with value types | |
const MyType* const example4 = &a; | |
example4 = &b; // ERROR: Pointer value (address) is const | |
example4->Mutate(); // ERROR: Object is const | |
} | |
//------------------------------------------------------------------------------------------------------------------------------ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment