Skip to content

Instantly share code, notes, and snippets.

@tmsampson
Last active April 27, 2023 13:15
Show Gist options
  • Save tmsampson/124e78bc10436f8ecb772e32f1d70ee7 to your computer and use it in GitHub Desktop.
Save tmsampson/124e78bc10436f8ecb772e32f1d70ee7 to your computer and use it in GitHub Desktop.
C++ Const Pointer Usage
//------------------------------------------------------------------------------------------------------------------------------
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