Duration of storage of underlying data characters with a custom string literal

Quick setup: I want to pass strings in my program as a pointer and size. I have a String class and a user-defined literal for building string strings:

struct String { const char *ptr; size_t sz; }; inline constexpr String operator "" _string(const char *s, size_t sz) { return {s, sz}; } int main() { auto s = "hello"_string; s.ptr[0]; //<-- is this access guaranteed to work? } 

Does the standard indicate that the argument passed to my user-defined literal operator has a static duration? i.e. the above code is actually equivalent to writing:

 int main() { String s{"hello", 5}; } 

or was the compiler / linker allowed to leave me with a dangling pointer when I use a user-defined literal?

(Section 2.13.8 of N4527 did not seem to say anything about the argument storage class for user-defined string literal operators. It would be useful to evaluate any pointers in the relevant sections of the standard.)

+7
c ++ c ++ 11 c ++ 14 user-defined-literals storage-duration
source share
1 answer

From [lex.ext]:

If L is a user-defined string literal, let str be a literal without its ud suffix and let len ​​be the number of code units in str (that is, its length, excluding the finite null character). The literal L considered as a call of the form:

 operator "" X (str , len ) 

From [lex.string]:

Evaluating a string literal results in a string literal object with a static storage duration initialized from the given characters, as described above.

So:

 "hello"_string; 

equivalent to:

 operator "" _string("hello", 5) 

Since "hello" is a string literal, it has a static storage duration, so you will not have a dangling pointer.

+4
source share

All Articles