1

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?

7
  • Interesting question. I'd take a peek a your <string> header file and see what you see, Commented Jul 10, 2023 at 15:07
  • This question is compiler specific (as much as I know C++ language does not support this), so it would be helpful to specify which one you are using. Commented Jul 10, 2023 at 15:09
  • Ideally it'd be universal but we definitely focus on Clang. Commented Jul 10, 2023 at 15:11
  • For it to be universal it has to be supported on the language level, and it is obviously not supported. Commented Jul 10, 2023 at 15:16
  • There's nothing that stands out in libc++. _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 const value_type* c_str() const _NOEXCEPT {return data();} I checked the call chain and there didn't seem to be any special attributes for this. Commented Jul 10, 2023 at 15:39

1 Answer 1

0

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;
Sign up to request clarification or add additional context in comments.

3 Comments

This would forbid valid usage as well, like printf("%s", foo().c_str())
@StilesCrisis +1 - ideone.com/IRtALB
@StilesCrisis: I agree. C++, contrary to Rust doesn't have lifetime within the type to spot dangling pointer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.