c++ - 为什么 ncurses 小部件在单独的函数中创建时不能正常工作?

标签 c++ ncurses curses

我正在尝试使用 C++ 中的纯 ncurses 创建一系列嵌套菜单。如果我创建一个菜单并将其发布到 main() 中,它就可以正常工作。但是,如果我采用相同的代码并将其放入返回 MENU* 的函数中,则它根本不起作用。我错过了什么吗?

有效的代码:

int main() 
{
  /*
   * snipped out the curses startup code
   */ 
  vector<char*> options;
  options.push_back("List");
  options.push_back("Add");
  options.push_back("Delete");
  options.push_back("Exit");

  vector<ITEM*> menu_items(options.size());
  for (int i = 0; i < options.size(); i++)
    menu_items[i] = new_item(options[i], NULL);

  MENU *options_menu;
  options_menu = new_menu(&menu_items[0]);

  set_menu_win(options_menu, main_window);
  set_menu_sub(options_menu, derwin(main_window, 6, 20, 3, 3));
  set_menu_mark(options_menu, ">");

  refresh();
  post_menu(options_menu); // this works fine
  wrefresh(main_window);
  /* 
   * snipped out the rest of the stuff
   */
}

无效的代码:

MENU *make_menu()
{
  /*
   * same as code in previous main()
   */

  return options_menu;
}

int main()
{
  /*
   * snip
   */

  MENU *options_menu = make_menu();
  refresh();
  post_menu(options_menu); // this doesn't do anything
  wrefresh(main_window);

  /*
   * snip
   */
}

最佳答案

我会为以后的搜索者回答这个问题。结果是 new_menu 接受一个指向 ITEM 列表的指针并卡在它上面。如果 ITEM 列表在函数的堆栈上,当函数返回时它将被删除,使 ITEM 列表无效。

这个问题的解决方案是在堆上创建 ITEM 列表,要么通过 C++ 中的 new,要么使用 malloc(记得要 delete免费!)。另一种选择是将 MENU 包装在一个类中,并将 ITEM 列表保留为成员变量。

最简单的解决方案是将 MENU(或 ITEM 列表)设为全局。

关于c++ - 为什么 ncurses 小部件在单独的函数中创建时不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17601221/

相关文章:

C++ << 在队列模板中重载

c - 在ncurses中设置光标移动字段

c - "curs_set()"返回前一个游标状态失败

Python curses 从 stdin 读取单个字符会影响 print 语句的输出

c++ - 如何将用于演示的运动历史图像制作成一张图像?

c++ - 如何使用 __builtin_ctz 加速二进制 GCD 算法?

c++ - ncurses new_menu 段错误

python - Setupterm 找不到终端,在 Python 程序中使用 curses

python - 在 python curses 中使用哪个 $TERM 来同时拥有 256 种颜色和鼠标移动事件?

c++ - 如何限制模板仿函数返回和参数类型