How to implement dangling-pointer warning in custom string type

89 views Asked by At

The following code is invalid because it takes a pointer into a temporary object (triggering -Wdangling-gsl):

static std::string f() {
    return "hi";
}

void func() {
    const char* ptr = f().c_str();
}
<source>:8:23: warning: object backing the pointer will be destroyed at the end of the full-expression [-Wdangling-gsl]

I have a custom string class which looks and feels a lot like std::string, but internally represents the text in a different way.

Is there a way to make MyString::c_str also generate a similar warning if used in this way?

1

There are 1 answers

3
Jarod42 On

I don't think so for warning (unless compiler has extension for that), but you can forbid that function on temporary (which would forbid also valid usage).

const char* MyString::c_str() const && = delete;