Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if pointer-to-const points to const object?

Tags:

c++

c++20

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));
}
like image 923
Andrew Tomazos Avatar asked Mar 02 '23 19:03

Andrew Tomazos


1 Answers

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.

  1. You could add your own dynamic runtime information to every const instance.

  2. You could hack the loading of your executable and detect items by segment in memory.

  3. You could carefully write your code to be constexpr if the pointer is to a constexpr global variable and detect that.

  4. 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.

like image 178
Yakk - Adam Nevraumont Avatar answered Mar 12 '23 22:03

Yakk - Adam Nevraumont