Waldorf
Waldorf

Reputation: 893

Is there a way to pass a string literal as reference in C++

Within C++ it is common to pass by reference instead of pointer if a value can not be NULL.

Suppose I have a function with the following signature, which is often used with a string literal.

void setText( const char* text );

I was wondering how I could change the function in such a way that it accepts a reference (and has the advantage not to accept NULL)?

Any other common ways, or just stick to the std::string& or the char* ?

Upvotes: 2

Views: 4291

Answers (2)

Zan Lynx
Zan Lynx

Reputation: 54345

Honestly, I would just keep the const char* text function and add an overload const std::string& text function that calls the first one with setText(text.c_str())

Upvotes: 2

JHumphrey
JHumphrey

Reputation: 999

There's a slight problem here in that C++ and references-to-arrays aren't the best pair. For reference, see: C++ pass an array by reference

Since you're talking about binding a reference to a string, and a string is an array of characters, we run into that problem head-on. In light of this, the best we can really do is bind a ref to a const char*, which looks like this:

void ref(const char* const& s);

But this doesn't do what you want; this binds a reference to a pointer, and all it guarantees is that the pointer itself exists, not that it's pointing to a valid string literal. This same problem is present in the std::string& examples: those only guarantee that you've bound to a std::string object, but that string could very well be empty, so you still haven't guaranteed yourself a string that has anything of value in it.

In the end, I'll second what Zan says. const char* is a well respected idiom passing string literals, and then having a second overload that binds to strings is a nice convenience.

(One last note: std::string doesn't "always" allocate memory. Implementations with the small string optimization will skip it for strings as long as 23 characters.)

Upvotes: -1

Related Questions