C++ Logo

std-proposals

Advanced search

Re: [std-proposals] all bytes zero == null object

From: Heckerpowered <heckerpowered_at_[hidden]>
Date: Tue, 23 Jul 2024 01:08:41 +0800
On Mon, 22 Jul 2024 at 17:23, someone with garbled name via Std-Proposals <std-proposals_at_[hidden]> wrote:
> Maybe we can go further. Here is my solution.
> We add a template struct in namespace std.
>
> template<class T>
> struct invalid_state; //No definition


Introducing an invalid_state template in namespace std is good, but I think it’s inappropriate compare to the element’s binary to determine whether a std::optional has a value. Sometimes we need to determine whether a std::optional is empty with multiple members, and the memory layout of the members may be discontinuous.

In addition, there’s another problem, it may be a little troublesome to obtain the binary of a invalid value and hard-code it into the source, and it has poor semantics, may be a series of 0xff in the example is easy to understand, but I don’t think it’ll always be that way. All in all, I think the implementation in the example is somewhat limited.

Instead of comparing the binary of members, I think it would be better to use unary predicate, for example:

'
template<typename T>
struct invalid_state; // in namespace std

template<>
struct invalid_state<my_class>
{
        bool operator()(const my_class& my_object) no except {
                return my_object.member == /* a invalid value */;
        }
};
'
The new implementation can do anything the previous implementation can do, and has better semantic. Such as a vector, comparing its size with std::numeric_limits<std::size_t>::max() is absolutely better than a series of 0xff, and people, and it’s difficult for humans to determine how many 0xff(s) are there in a series of 0xff quickly, so better semantics can help reduce potential problems.

Received on 2024-07-22 17:09:03