Returning const char* from a string literal in C++? [duplicate]
Asked Answered
C

1

8

Normally, I would return a std::string from a function because returning a const char* would require the caller to provide an output memory buffer, and that buffer is not resizable.

But is returning a const char* valid if its from a string literal?

const char* generate_c_string() {
    return "ABC";
}

Doing in this way (if valid) would likely be faster as I would not need to dynamically allocate memory to construct a std::string.

It probably is valid, because const char* x = "ABC"; is valid. Is there a reference from the C++ standard that substantiates its validity?

Crispation answered 20/12, 2017 at 5:7 Comment(7)
I don’t understand why the caller would require to provide any buffer if you return a pointer.Outherod
Despite voting to close as a duplicate, I upvoted question and answer because both are still usefulApart
Note that for such short strings the most common std::string implementations do not allocate any dynamic memory. Meaning of the acronym SSO in the context of std::stringUmbilical
It's quite possible that a std::string_view suffices if you don't need a full std::string. Of course it still has the same lifetime requirements since it doesn't use its own storage.Carissacarita
@Sami If the function wasn't as simple as returning a static string (perhaps we need to concatenate some text), then the caller should pass a output char* argument to the function.Crispation
Oh, yes, as an argument, but then one wouldn’t return a pointer. That’s what baffled me.Outherod
@Sami Sorry, I wasn't clear about that in the question. But wouldn't I still need to return a pointer to the past-the-end character?Crispation
K
13

This is valid, for string literals,

String literals have static storage duration, and thus exist in memory for the life of the program.

The pointer returned would remain valid in the life of the program.

Kado answered 20/12, 2017 at 5:13 Comment(2)
Does this cover borderline scenarios such as generate_c_string being imported from a dynamic library that later gets unloaded?Abbotson
@VTT That sounds worthy of a questionFrants

© 2022 - 2024 — McMap. All rights reserved.