提问人:StilesCrisis 提问时间:7/10/2023 更新时间:7/10/2023 访问量:62
如何在自定义字符串类型中实现悬空指针警告
How to implement dangling-pointer warning in custom string type
问:
以下代码无效,因为它需要指向临时对象的指针(触发):-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]
我有一个自定义字符串类,它的外观和感觉很像,但在内部以不同的方式表示文本。std::string
如果以这种方式使用,有没有办法也生成类似的警告?MyString::c_str
答:
0赞
Jarod42
7/10/2023
#1
我不这么认为警告(除非编译器对此有扩展),但您可以暂时禁止该功能(这也将禁止有效使用)。
const char* MyString::c_str() const && = delete;
评论
4赞
StilesCrisis
7/10/2023
这也将禁止有效使用,例如printf("%s", foo().c_str())
0赞
Slava
7/10/2023
@StilesCrisis +1 - ideone.com/IRtALB
0赞
Jarod42
7/10/2023
@StilesCrisis:我同意。与 Rust 相反,C++ 在类型中没有生存期来发现悬空指针。
评论
<string>
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 const value_type* c_str() const _NOEXCEPT {return data();}