Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.