Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in C++ to enforce a string-literal function argument?

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?

like image 412
par Avatar asked Nov 15 '22 19:11

par


1 Answers

Just make the constructor explicitly taking rvalue:

struct Example {
   Example(const char*&& s) : string(s) { }

   const char* string;
};
like image 175
Damir Tenishev Avatar answered Dec 10 '22 23:12

Damir Tenishev