我正在阅读终生安全核心指南文件,并渴望-Wlifetime在实践中尝试该标志。首先,我编写了以下简单示例:
class Wrapper
{
public:
Wrapper(std::string s)
: str_(std::move(s))
{ }
const std::string& GetString() const
{
return str_;
}
private:
std::string str_;
};
const std::string& example() {
return Wrapper("abc").GetString();
}
Run Code Online (Sandbox Code Playgroud)
它确实发出了一些警告,但显然它们出现在 stdlib 中并且与我的代码无关:
In file included from <built-in>:1:
/opt/compiler-explorer/clang-cppx-trunk/include/experimental/meta:3233:38: warning: returning a pointer with points-to set (*(*this).m_first) where points-to set ((null), **this) is expected [-Wlifetime]
consteval iterator begin() const { return m_first; }
^~~~~~~~~~~~~~
/opt/compiler-explorer/clang-cppx-trunk/include/experimental/meta:3235:36: warning: returning a pointer with points-to set (*(*this).m_last) where points-to set ((null), **this) is expected [-Wlifetime]
consteval iterator end() const { return m_last; }
^~~~~~~~~~~~~
/opt/compiler-explorer/clang-cppx-trunk/include/experimental/meta:3263:3: warning: returning a dangling pointer [-Wlifetime]
return range(reflection, pred);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/opt/compiler-explorer/clang-cppx-trunk/include/experimental/meta:3276:10: note: in instantiation of function template specialization 'std::experimental::meta::v1::members_of<std::experimental::meta::v1::detail::always_true_fn>' requested here
return members_of(reflection, detail::always_true);
^
/opt/compiler-explorer/clang-cppx-trunk/include/experimental/meta:3263:10: note: it was never initialized here
return range(reflection, pred);
^~~~~~~~~~~~~~~~~~~~~~~
/opt/compiler-explorer/clang-cppx-trunk/include/experimental/meta:3281:3: warning: returning a dangling pointer [-Wlifetime]
return param_range(reflection);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/opt/compiler-explorer/clang-cppx-trunk/include/experimental/meta:3281:10: note: it was never initialized here
return param_range(reflection);
^~~~~~~~~~~~~~~~~~~~~~~
/opt/compiler-explorer/clang-cppx-trunk/include/experimental/meta:3289:3: warning: returning a dangling pointer [-Wlifetime]
return __reflect(detail::query_get_begin, reflection);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/opt/compiler-explorer/clang-cppx-trunk/include/experimental/meta:3289:10: note: it was never initialized here
return __reflect(detail::query_get_begin, reflection);
Run Code Online (Sandbox Code Playgroud)
(无论我写什么代码,这些警告仍然存在,所以我认为它们无关紧要)
我对我的代码中没有警告感到惊讶。就我理解的论文而言,返回的字符串的生命周期应该为Wrapper,因为它是Wrapper::GetString(1.1.4:“默认情况下,我们假设函数返回从其参数派生的值”)的隐式参数。我什[[gsl::Owner(std::string)]]至添加到类定义中,但没有运气。
为什么我的代码不产生警告,在这种情况下有没有办法使静态分析工作?