c++ - 为什么这段代码没有使用 `-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)]]
了类定义,但没有运气。
为什么我的代码没有产生警告,在这种情况下有没有办法让静态分析工作?
解决方案
推荐阅读
- google-cloud-platform - 如何在 Google Cloud Platform CLI 中切换配置 - Cloud Shell
- python - 当列表中没有值时,list.count() 表示 1
- python - 在嵌套字典中添加项目
- c++ - 按唯一标识符描述数字列表
- php - PHP 仅将 SQL 拉为文本
- javascript - 在以下代码中制作反应应用程序时收到“解析错误:意外的令牌,预期的”;“”
- r - x * w 中的 dudi.hillsmith 错误:二元运算符的非数字参数
- amazon-web-services - Amazon S3 生命周期规则:存档文件具有最近的日期
- javascript - 通过选择选项 javascript 更改品牌详细信息
- c# - 映射列表
- > 到具有最大值对象属性的字典