首页 > 解决方案 > 为什么这段代码没有使用 `-Wlifetime` 触发警告?

问题描述

我正在阅读终生安全核心指南文件,并渴望在实践中尝试使用该-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();
}

它确实发出了一些警告,但显然它们出现在 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);

(无论我写什么代码,这些警告仍然存在,所以我认为它们无关紧要)

我对我的代码中没有警告感到惊讶。据我理解这篇论文,返回的字符串应该有一个生命周期Wrapper,因为它是Wrapper::GetString(1.1.4:“默认情况下我们假设一个函数返回从它的参数派生的值”)的隐式参数。我什至添加[[gsl::Owner(std::string)]]了类定义,但没有运气。

-Wlifetime已启用的Godbolt 示例

为什么我的代码没有产生警告,在这种情况下有没有办法让静态分析工作?

标签: c++lifetime

解决方案


推荐阅读