I'm wondering if it's possible in C++ to declare a function parameter that must be a string literal? My goal is to receive an object that I can keep only the pointer to and know it won't be free()
ed out from under me (i.e. has application lifetime scope).
For example, say I have something like:
#include <string.h>
struct Example {
Example(const char *s) : string(s) { }
const char *string;
};
void f() {
char *freeableFoo = strdup("foo");
Example e(freeableFoo); // e.string's lifetime is unknown
Example e1("literalFoo"); // e1.string is always valid
free(freeableFoo);
// e.string is now invalid
}
As shown in the example, when freeableFoo
is free()
ed the e.string
member becomes invalid. This happens without Example
's awareness.
Obviously we can get around this if Example
copies the string in its constructor, but I'd like to not allocate memory for a copy.
Is a declaration possible for Example
's constructor that says "you must pass a string literal" (enforced at compile-time) so Example
knows it doesn't have to copy the string and it knows its string
pointer will be valid for the application's lifetime?
Just make the constructor explicitly taking rvalue:
struct Example {
Example(const char*&& s) : string(s) { }
const char* string;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With