Andrew Tomazos
Andrew Tomazos

Reputation: 68648

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

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));
}

Upvotes: 4

Views: 285

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275405

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.

Upvotes: 7

Related Questions