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

  arguments, c++, parameter-passing, string-literals

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


    // 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?

Source: Windows Questions C++