C++ Logo


Advanced search

Subject: Re: [ub] Justification for < not being a total order on pointers?
From: Gabriel Dos Reis (gdr_at_[hidden])
Date: 2013-10-17 23:29:00

Nevin Liber <nevin_at_[hidden]> writes:

| On 15 October 2013 17:39, Nevin Liber <nevin_at_[hidden]> wrote:
| Really?  I've seen novices ask questions like "does pointer p point to an
| object inside array a?"  A natural (but wrong) way to write it is:
| bool isInArray = std::begin(a) <= p && p < std::end(a);

That is a wrong question to ask, and I am not too surprise that what you
think would be natural question would be wrong. It is also not too
surprising for a novice to ask a wrong question -- not every question
that a novice ask makes sense.

What you tell your novice if he asked you: "does this iterator p points
to an object in this container"?

| Can you even write this w/o possibly invoking ub?  The only way I can think
| of is O(n), as in:
| bool isInArray = false;
| for (auto q = std::begin(a); q != std::end(a); ++q)
|     if (p == q) {
|         isInArray = true;
|         break;
|     }
| Could I also please get an answer to this question?  This one isn't
| theoretical, either.

I hope you aware that you are quite prolific in this thread, and I hope
you are not making a demand that everything single post of question you
ask must be answered right away.

| It turns out that not only was this a novice question, but the novice in
| question pointed to almost identical code that was believed by the author to be
| C++11 compliant.  Since it isn't, how should we recommend he fix it?

In my view, what is to be fixed is the question and how the author
happen to find himself in the position to ask that question. It simply
isn't a good question to ask, and I would not mind if the system makes
it harder to ask and/or answer.

| I don't believe that casting it to intptr_t or uintptr_t is sufficient, since
| you don't get a guarantee that the result is required to preserve the natural
| order of the pointers.  Is the O(n) solution the only standards conformant way
| to do it?

-- Gaby

SG12 list run by herb.sutter at gmail.com