gpt4 book ai didi

c - 如何初始化 Bison 的 %union 值?

转载 作者:太空宇宙 更新时间:2023-11-04 03:08:31 27 4
gpt4 key购买 nike

在 Bison 我有一个 union

%union
{
std::string* sval;
}

我想这样使用它

在 Lex 中:

*(yylval->sval) = "ABCD";

而不是

yylval->sval = new std::string("ABCD");

轻松防止内存泄漏

但是我需要一些方法来分配一个 std::string 给 sval 开始。

我该怎么做?

最佳答案

您不能安全地将具有构造函数或析构函数的类型(例如 std::string)放入 union 中,因此这行不通。

您可以做的是根本不使用 %union —— 而是使用宏将 YYSTYPE 直接映射到其他类型:

%{
#define YYSTYPE std::string
%}

然后 yylval 将是那个类型(语法代码中的所有 $n 选项也是如此)

关于c - 如何初始化 Bison 的 %union 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1257653/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com