【问题标题】:Error Taking the Address of a Temporary Array (array of lambdas)获取临时数组(lambda 数组)的地址时出错
【发布时间】:2016-09-30 03:24:42
【问题描述】:

所以,我有一个类,它接受一个整数、一个整数向量和一个 lambda 函数数组作为其构造函数,如下所示:

class Cell {
private:
    short m_State;
    std::function< bool(const char) > m_func;

public:
    Cell(short state, std::function< bool(const char) > func) { m_State = state; m_func = func; };
    Cell() { m_State = 0; m_func = [] (char) -> bool { return false; }; };
    bool operator() (const char input) { return m_func(input); };
    short State() { return m_State; };
};


class Row {
private:
    Cell * m_Cells;
    short m_States;

public:
    Row( short num_states, std::vector<short> states, std::function< bool(char) > * funcs ) {
        m_States = num_states;
        m_Cells = new Cell[num_states];
        for (short i = 0; i < m_States; i++) {
            m_Cells[i] = Cell( states[i], funcs[i] );
        }
    };

    ~Row() {
        delete[] m_Cells;
        m_Cells = NULL;
        m_States = 0;
    };

    short operator[] (const char input) const {
        for (short i = 0; i < m_States; i++)
            if (m_Cells[i](input))
                return m_Cells[i].State();
        return -1;
    };
};

现在,假设我有一些 lambda:

auto kIS_BETWEEN = [](char s, char e) { return [s, e](char x) -> bool { return (x >= s && x <= e); }; };
auto kIS_NOT_0_DIGIT_FUNC = kIS_BETWEEN('1', '9')

进一步假设我有一个像这样的预处理器定义:

#define FUNC_TYPE(x) const std::function< bool(const char) >[x]

现在,当我尝试定义 Row 变量时:

Row x = Row( 1, {1}, (FUNC_TYPE(1)){kIS_NOT_0_DIGIT_FUNC} );

我收到“获取临时数组的地址”错误。我做错了什么,我该如何解决?

【问题讨论】:

  • 看起来您可能正在获取临时数组的地址。这也应该是一个警告,而不是错误,AFAIK。
  • @immibis 我知道这就是错误的意思,但这是一个错误。无论如何,我没有从操作中得到任何输出。
  • @Woody1193 如果是错误,你怎么能得到输出?
  • 你希望(const std::function&lt; bool(const char) &gt;[1]){kIS_NOT_0_DIGIT_FUNC} 表现什么?
  • @appleapple 我是从here 那里得到的。

标签: c++ arrays lambda


【解决方案1】:

关键是改变我的Row 类,这样:

class Row {
private:
    std::vector<Cell> m_Cells;
    short m_States;

public:
    Row( short num_states, std::vector<short> states, std::vector< std::function< bool(char) > > funcs ) {
        m_States = num_states;
        for (short i = 0; i < m_States; i++) {
            m_Cells.push_back(const Cell( states[i], funcs[i] ));
        }
    };

    short operator[] (const char input) const {
        for (short i = 0; i < m_States; i++)
            if (m_Cells[i](input))
                return m_Cells[i].State();
        return -1;
    };
};

【讨论】:

    猜你喜欢
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 2013-05-05
    • 2011-03-21
    • 1970-01-01
    相关资源
    最近更新 更多