首页 > 解决方案 > c ++ lambda已使用但未初始化

问题描述

这是我的代码,我得到 klocworks 错误 'value' is used uninitialized in this function。

/// Converts rgb to grayscale (in all channels)
template <typename T>
void convert_to_grayscale(rgb_image_s<T> &img)
{
    auto r = img[rgb_color_e::red];
    auto g = img[rgb_color_e::green];
    auto b = img[rgb_color_e::blue];
    r.foreach([](T &r, T &g, T &b)
    {
        /// error: 'value' is used uninitialized in this function.
        auto value = reduce_to<T>(0.299 * r + 0.587 * g + 0.114 * b);
        r = value;
        g = value;
        b = value;
    }, g, b);
}

reduce_to 函数

 // For integral types T only
    template<typename T>  // T <- T do nothing
    typename std::enable_if<std::is_integral<T>::value, T>::type reduce_to(T t) { return t; }

foreach 函数

 template <class func, typename... types> func&
            foreach(func &&f, types&&... images) const
        {
            // Check that the other input images are at least same size as this is
            validate_sizes(images.size()...);

            auto skipx = std::initializer_list<int>({ _skip_x, images._skip_x... });
            auto all_ones = std::all_of(skipx.begin(), skipx.end(), [](const int skip) { return skip == 1; });
            if (all_ones)
            {
                for (auto y : _height)
                {
                    iterate_row(_width, f, &at(y, 0), &images.at(y, 0)...);
                }
            }
            else
            {
                for (auto y : _height)
                {
                    iterate_row(_width, f, make_row_iterator(y), images.make_row_iterator(y)...);
                }
            }
            return f;
        }

我的解决方案是:

   /// Converts rgb to grayscale (in all channels)
    template <typename T>
    void convert_to_grayscale(rgb_image_s<T> &img)
    {
        auto r = img[rgb_color_e::red];
        auto g = img[rgb_color_e::green];
        auto b = img[rgb_color_e::blue];
        r.foreach([](T &r, T &g, T &b)
        {
            T value = reduce_to<T>(0.299 * r + 0.587 * g + 0.114 * b); // changed to T instead of auto
            r = value;
            g = value;
            b = value;
        }, g, b);
    }

我试图理解为什么 klocworks 认为这是一个错误?

你觉得我的解决方法好吗?我测试了它,它看起来可以工作。

标签: c++klocwork

解决方案


推荐阅读