C++ Logo


Advanced search

Re: why does std::basic_string should accept an std::basic_string_view with the same charT and Traits

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Mon, 14 Sep 2020 09:56:51 -0400
On Mon, Sep 14, 2020 at 2:41 AM Robert Behar via Std-Proposals
<std-proposals_at_[hidden]> wrote:
> >however I don't think you should be able to compare these directly.
> >is like comparing unsigned with float point or bool with int.
> Why? Because the allocator is part of the type? Well, is there a good reason for it to be part of the type? why not type erase it like the std::shared_ptr Deleter and Allocator

Ignoring the backwards-compatibility issues with doing that, it bloats
the string type. Type erasure will generally require allocating
memory. `shared_ptr` already has memory allocation overhead for the
control block, so adding a little more isn't too onerous. And even if
allocating memory isn't required for a specific allocator type, the
implementation will still need to have some extra data that represents
the allocator's storage within the object, even if the allocator is
stateless. By contrast, if the allocator's type is statically known,
and it's an empty type, you can make it take up no actual storage
within the `basic_string`.

So making the allocator part of the string's type makes it a more
efficient string type, while still allowing the flexibility of
controlling where a particular string gets its storage. And we already
have a mechanism for doing "type erasure" if you want to pay for it:

But yes, I do agree that saying "is like comparing unsigned with float
point or bool with int" is wrong. They are *conceptually* storing the
same data; they are only different types because of the need to do
special static things with their allocators. The allocator type being
part of the string's type is a wart of the language, not a fundamental
part of what it means to be a "string". So long as the character and
traits types are the same, I think it is perfectly valid to compare

Received on 2020-09-14 08:57:05