Search code examples
c++pointersc++-conceptsraw-pointer

What would be the proper implementation of a concept describing a raw pointer (to objects)?


This might be of academic interest only.

Because I noticed that my practical example might not be the suitable one to raise that question.

Originally I had written something like

auto bak_ptr{ptr}; // think of an `int* ptr`

to make a backup of an address. Now I wondered if I could do better by replacing that dumb auto by a more meaningful, horizon broadening C++20 concept.

After some thought, the right choice in that specific example might just be

std::copyable auto bak_ptr{ptr};

because that's mirroring the intent of a backup, a copy of something.

But the academic question remaining is: What would be a proper (concepts standard library) implementation correctly mapping the behavior of the raw pointer concept? And let's restrict 'pointer' to pointer to objects for know, if necessary. There are also pointers to void, functions, members - perhaps complicating the issue.

I thought of a relationship to iterators. Hopefully not yet again answering my own question correctly: would std::contiguous_iterator be a valuable choice in cases? Could someone please share a more or less complete expert view on that topic?

And why there might be no std::pointer_to_object standard library implementation for that concept yet (yelling the thing into your face)?


Solution

  • Just building up upon std::is_pointer there should be nothing wrong with

    template <class T>
    concept pointer =
      std::is_pointer_v<T>;
    

    Thanks to @cigien for that idea.

    And I would say that in the simple backup example the choice of std::copyable instead is exactly right. As that's what you want to do with the backup, restore it again by copy.