Is there anyway to determine if a pointer-to-const points to a const object?
bool is_const_object(const int* p) {
return ???;
}
int main() {
int x = 42;
const int y = 43;
assert(!is_const_object(&x));
assert(is_const_object(&y));
}
No, there isn't a way. C++ does not store runtime dynamic information about something being const. C++ does not know statically within the function if the data is really const or not.
There are a few cases where it can be done with limitations.
You could add your own dynamic runtime information to every const instance.
You could hack the loading of your executable and detect items by segment in memory.
You could carefully write your code to be constexpr if the pointer is to a constexpr global variable and detect that.
You could write a template function that takes a T*
and detect if it is const or not.
None of these do what you are asking to do, but they do things adjacent to what you are asking to do that may fix your real problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With