storage duration of underlying character data with user-defined string literal
Asked Answered
S

1

9

Quick setup: I want to pass strings around in my program as a pointer and a size. I have a String class and a user-defined literal for constructing literal 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 specify that the argument passed to my user-defined literal operator has static duration? i.e. is the above code actually equivalent to writing:

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

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

(Section 2.13.8 of N4527 did not seem to say anything on the subject of storage class of the argument to the user-defined string literal operators. Any pointers into the appropriate section(s) of the standard would be appreciated.)

Satirist answered 18/9, 2015 at 12:29 Comment(4)
Section 2.13.8 aka [lex.ext]p5 does seem to say that the argument is a string-literal, and those have static storage duration.Christogram
@Christogram I am not sure if that is clear though, I keep going back and forth on thatSurmount
@ShafikYaghmour That's why I didn't post it as an answer ;)Christogram
@ShafikYaghmour What room for doubt? What am I missing? It calls them string literals, string literals have static storage duration, no?Yeast
Y
6

From [lex.ext]:

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

operator "" X (str , len )

From [lex.string]:

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

So:

"hello"_string;

is equivalent to:

operator "" _string("hello", 5)

As "hello" is a string-literal, it has static storage duration, so you will have no dangling pointer.

Yeast answered 18/9, 2015 at 12:43 Comment(4)
"of the form" seems a bit vague, it doesn't say "equivalent to". Anyway, I agree with the basic notion.Christogram
@Christogram Yeah, in other contexts in the standard "of the form" is usually presenting a syntactical structure (e.g. "an expression of the form E1 op= E2 is equivalent to E1 = E1 op E2 ... "). Poor wording choice imo.Yeast
There's [dcl.fct.def.general]p8, though, which is not syntactical; it might mean "equivalent to" in that instance.Christogram
The standard seems clear enough when you say it. Accepted, thanks!Satirist

© 2022 - 2024 — McMap. All rights reserved.