[llvm-dev] Is it time to allow StringRef to be constructed from nullptr?

Zachary Turner via llvm-dev llvm-dev at lists.llvm.org
Sun Sep 25 14:55:08 PDT 2016


On Sun, Sep 25, 2016 at 12:53 PM Chris Lattner <clattner at apple.com> wrote:

>
> On Sep 25, 2016, at 6:10 AM, Zachary Turner via llvm-dev <
> llvm-dev at lists.llvm.org> wrote:
> With that out of the way, here are some reasons I can see to allow
> StringRef accept null to its constructor which are independent of LLDB and
> stand on their own merit.
>
> 1) std::string_view<> can be constructed with null.  I don't know when we
> will be able to use std::string_view<>, but there's a chance that at some
> point in the future we may wish to remove StringRef in favor of
> string_view.  That day isn't soon, but in any case, it will be easier if
> our assumptions are the same.
>
> 2) [nullptr, nullptr+0) is a valid range.  Why shouldn't we be able to
> construct a StringRef from an otherwise perfectly valid range?
>
> 3) StringRef() can *already* be constructed from nullptr (!)  Surprised?
> That's what happens when you invoke the default constructor.  It happily
> initializes the internal Data with null.  So why not allow the same
> behavior when invoking the const char * constructor?
>
>
> Thoughts?
>
>
> Seems fine to me, I think the default constructor behavior makes it clear
> that this is fine.  I don’t recall why the assert was originally added, but
> I don’t think it has added much (if any) value over the years.
>
> -Chris
>

 I just noticed it's not just the default constructor.  Even the const
char*, size_t constructor allows null as long as you specify a 0 length.

    LLVM_ATTRIBUTE_ALWAYS_INLINE
    /*implicit*/ StringRef(const char *data, size_t length)
      : Data(data), Length(length) {
        assert((data || length == 0) &&
        "StringRef cannot be built from a NULL argument with non-null
length");
      }

It seems that the only benefit of the asserting constructor is that it
saves a branch when invoked with a character pointer (I would expect the
branch to be optimized away when constructed with a string literal or char
array).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20160925/dfe7db62/attachment.html>


More information about the llvm-dev mailing list