我有一个典型的可重入的C语言解析器,其中解析后的数据包含在如下union结构中:
%union {
int number;
const char *string;
Item *item_ptr;
}
我想使用共享指针替代普通指针。
由于无法使用C++11
编译源代码,也被禁止使用boost::shared_ptr
,因此我有自己的类SharedPtr
,实现所需的行为。
不幸的是,我无法将SharedPtr
类插入以下联合中:
%union {
int number;
const char *string;
SharedPtr<Item> item_ptr;
}
由于我遇到了以下错误:
bisonparser.yy:92:20: error: member ‘SharedPtr<Item> YYSTYPE::item_ptr’ with constructor not allowed in union
bisonparser.yy:92:20: error: member ‘SharedPtr<Item> YYSTYPE::item_ptr’ with destructor not allowed in union
bisonparser.yy:92:20: error: member ‘SharedPtr<Item> YYSTYPE::item_ptr’ with copy assignment operator not allowed in union
bisonparser.yy:92:20: note: unrestricted unions only available with -std=c++11 or -std=gnu++11
另一种方法是插入间接层,如下所示:
%union {
int number;
const char *string;
SharedPtr<Item> *item_ptr;
}
不过,我想知道是否有更加简洁的方式来设计我的项目,以便直接使用我的SharedPtr
类而不是作为指针。 我需要找到哪些最小的更改才能得到替代方案?
union
,这种没有容器智能的粗糙变量存储区域,封装到一个具有容器智能的 variant 类中,并在%union
中放置指向这样一个类的指针。然后所有操作都将通过 variant 类指针进行,因此目前在%union
中的内容将被放入新的 variant 类中。但是,我不知道在 Bison 中如何使用%union
。它似乎被用来指定 Bison 生成的源代码中的union
。 - Richard Chambers%union { Node * ptr };
,其中class Node { public: SharedPtr<Item> item_ptr };
。使用时会有一些笨重。例如,不是$$ = new Item()
而是$$ = new Node(); $$->item_ptr.reset(new Item())
,还需要手动删除所有的Node
,可能会像以前一样存在内存泄漏的风险。这就是我对这个设计感到不太满意的原因。 - Anon