[LLVMdev] Correct use of StringRef and Twine

David Blaikie dblaikie at gmail.com
Mon Jul 25 23:36:14 PDT 2011


> StringRef is useful for other things, for example the parsing logic in ReadCheckFile in utils/FileCheck.cpp uses it effectively.  It really wants "reference into another string" that is efficient to .substr() etc.

Yep, I found some of those - functions that produce substrings:
StringRef trim(StringRef) or the like - in which case a Twine argument
doesn't make sense/cannot be correct.

I did run into one rather annoying quirk which seems to be a bug in GCC:

    struct foo
    {
            template<int N>
            foo(const char (&)[N]) { }
    };

    foo f()
    {
            return "x";
    }

This compiles successfully in VC2010 and clang, but not in GCC (4.5).
It seems as though GCC is being a bit too eager to degrade the char[2]
down to a char*. (even using an explicitly declared array, the same
issue occurs)

I had hoped to add a constructor like this to StringRef (& set the
length to N-1 if arr[N-1] was '\0', otherwise set it to N). I've added
it for now, but it's just a pity it's not getting picked up implicitly
(for now I've set StringRef's (const char*) ctor to explicit as a
means of finding a smattering of places to upgrade to Twine usage -
I'll set it back to implicit before sending the patch out).

- David




More information about the llvm-dev mailing list