c++ - cppcheck 警告:访问转发变量
问题描述
在下面的代码上
#include <utility>
template <int i = 0, class F, typename... ArgsType>
void g(F&& f, ArgsType&&... args)
{
if constexpr (i < 1) {
f(std::forward<ArgsType>(args)...);
g<1>(std::forward<F>(f), std::forward<ArgsType>(args)...);
}
}
运行会cppcheck --enable=all
给出以下警告:
Checking test.hpp ...
test.hpp:8:53: warning: Access of forwarded variable 'args'. [accessForwarded]
g<1>(std::forward<F>(f), std::forward<ArgsType>(args)...);
^
test.hpp:7:7: note: Calling std::forward(args)
f(std::forward<ArgsType>(args)...);
^
test.hpp:8:53: note: Access of forwarded variable 'args'.
g<1>(std::forward<F>(f), std::forward<ArgsType>(args)...);
^
这个警告是什么意思,为什么会被触发?
解决方案
当你这样做
f(std::forward<ArgsType>(args)...);
您正在将所有内容传递args...
给f
使用完美转发。这意味着如果任何一个args...
是右值,并且如果f
从该右值移动到函数参数或函数内部的变量中,那么该对象args...
现在将处于从状态移动,这意味着它的值现在已经消失了。当你然后重用args...
g<1>(std::forward<F>(f), std::forward<ArgsType>(args)...);
您现在可以使用已移动其内容且不再可用于读取的对象。这就是您收到警告的原因。如果你想调用这两个函数,你不能使用完美转发。
推荐阅读
- python - 我正在尝试使用 pdfminer 在 python 中将数据提取为 HTML 元素
- java - Java - 如果返回值为零,比较器如何工作?
- coq - 没有在 coq 中明确指定类型的实例
- java - 链接 2 个对象并从每个对象中获取它们
- google-tag-manager - 有没有办法将容器的标签和触发器共享到谷歌标签管理器中的另一个容器
- google-cloud-platform - 创建新数据实验室实例时参数无效
- python - 当一个新的小部件被分配给它时,框架背景颜色消失(tkinter)
- java - 此服务器无法验证您是否有权访问所请求的文档
- html - 如何使用 Python 搜索 HTML 元素?Python Web 机器人错误
- python - 如何在 XML 中搜索带有“和”的属性文本