Thomas Sampson

C++ Const Pointer Usage


Intro #

Even after working with C++ for years, it's still easy to get mixed up when applying const to pointers. Following code snippet provided as reference.
 

Code #

GitHub Gist: https://git.io/JJ3QW

//------------------------------------------------------------------------------------------------------------------------------

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
}

//------------------------------------------------------------------------------------------------------------------------------