首页 > 解决方案 > 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)...);
                                                    ^

这个警告是什么意思,为什么会被触发?

标签: c++warningsperfect-forwardingcppcheck

解决方案


当你这样做

f(std::forward<ArgsType>(args)...);

您正在将所有内容传递args...f使用完美转发。这意味着如果任何一个args...是右值,并且如果f从该右值移动到函数参数或函数内部的变量中,那么该对象args...现在将处于从状态移动,这意味着它的值现在已经消失了。当你然后重用args...

g<1>(std::forward<F>(f), std::forward<ArgsType>(args)...);

您现在可以使用已移动其内容且不再可用于读取的对象。这就是您收到警告的原因。如果你想调用这两个函数,你不能使用完美转发。


推荐阅读