What is the StringRef equivalent of NULL?
Peter
What is the StringRef equivalent of NULL?
Peter
StringRef()
-Chris
What is the StringRef equivalent of NULL?
StringRef()
-Chris
So why does StringRef(NULL) segfault?
Peter
IIRC, because it calls strlen(NULL).
-Eli
So why does StringRef(NULL) segfault?
IIRC, because it calls strlen(NULL).
To better phrase the question, why doesn't it check and return
StringRef() in that case?
Peter
Because that constructor is specified to take a non-null pointer :). It is a hot method and doing the null check would be wasteful.
-Chris
Because that constructor is specified to take a non-null pointer :). It is a hot method and doing the null check would be wasteful.
-Chris
In the vast majority of cases (static argument), that cost will be
eliminated by a decent optimizer. This makes converting functions that
accept NULL in their const char * args hard to convert. Ultimately
though, it's your choice.
Peter
I guess the argument here is the same as for std::string, that users who never ever pass null pointers see it as wasteful to have a test for every call. If someone believes his code can contain null pointers, the check could be before calling the constructor.
This is C++'s "you don't pay for what you don't use", to the extreme.
Bo Persson
If someone believes his code can contain null pointers, the check could be before calling the constructor.
The only exception is a copy constructor.
Consider this:
void foo(const char * bar) { ... }
I can convert it to this:
void foo(llvm::StringRef bar) { /* converted as needed */ ... }
Unless bar can be NULL, in which case I have to add set check too all
the callers (ugh!). To make matters worse, if I miss one, the program
still type-checks.
Peter
You can get your checks with an extra overload
void foo(const char* bar)
{ bar == 0 ? foo(llvm::StringRef()) : foo(llvm::Stringref(bar)); }
That way the cost is payed when possibly needed, and not by everyone creating a StringRef.
Bo Persson