Created
September 12, 2024 08:27
-
-
Save 0x61nas/6d4ebb9ed9d20bfd5391adbfab8504ce to your computer and use it in GitHub Desktop.
CPP constants is a mess
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
#include <iostream> | |
#define sos(x) std::cout << x << std::endl | |
class Entity { | |
private: | |
int m_x, m_y; | |
char *m_name; | |
// the mutable members is allowed to be modified in a const functions. | |
mutable int call_count = 0; | |
public: | |
// we promise that we'll not change any value, just a read operation | |
int get_x() const { return m_x; } | |
// return a constant pointer with a pointer context, and its a read only* | |
// function, cpp man :) | |
const char *const get_name() const { return m_name; } | |
int get_y() const { | |
// this may be useful for debugging, so we are not really break our promise | |
call_count += 1; | |
return m_y; | |
} | |
int _x() { return m_x; } | |
}; | |
void print_entity(const Entity &e) { | |
using namespace std::string_literals; | |
sos("X: "s << e.get_x()); | |
// if you are taking a constant reference, you can't call a none constant | |
// functions. sos(e._x()); // won't compile | |
} | |
int main(int argc, char *argv[]) { | |
const int MAX_AGE = 90; | |
int my_age = 21; | |
// create a new pointer to the heap | |
int *ptr = new int; | |
// change the pointer context | |
*ptr = 2; | |
// and we can change the pointer value | |
ptr = (int *)&MAX_AGE; // may cause a sig fault | |
// However, we can make the pointer context `const`, so we can not change it. | |
const int *const_ptr = new int; | |
// So, we can't change the context (a.k.a. the target value) | |
// *const_ptr = 2; | |
// But we still can change the pointer value. | |
// const_ptr = (int *)&MAX_AGE; // may cause a sig fault | |
const_ptr = &my_age; | |
sos(*const_ptr); | |
// We can promise that we will not change the pointer value by: | |
int *const ptr_const = new int; | |
// we can change the context (a.k.a. the target value) | |
*ptr_const = 2; | |
sos(*ptr_const); | |
// But we cannot change the pointer value | |
// ptr_const = &MAX_AGE; | |
// And we can promise that we'll not gonna change the pointer context or the | |
// pointer value. | |
const int *const const_ptr_const = new int; | |
// or | |
int const *const const_ptr_const_2 = new int; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment