分裂错误与琐碎的Spirit Parser语法

seh*_*ehe 3 c++ boost boost-spirit boost-spirit-qi

我正在使用我的Spirit Qi解析器遇到频繁的段错误.

花了好几天来调试问题(我发现堆栈跟踪无法理解)我决定将其修改为一个最小的例子.任何人都能说出我做错了什么,如果有的话?

将代码保存为bug.cpp,编译,g++ -Wall -o bug bug.cpp你应该好好去.

//#define BOOST_SPIRIT_DEBUG_PRINT_SOME 80
//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/version.hpp>
#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>

namespace /*anon*/
{
    using namespace boost::spirit::qi;

    template <typename Iterator, typename
        Skipper> struct bug_demo : 
            public grammar<Iterator, Skipper>
    {
        bug_demo() : 
            grammar<Iterator, Skipper>(story, "bug"),
            story(the),
            the("the")
        {
//          BOOST_SPIRIT_DEBUG_NODE(story);
//          BOOST_SPIRIT_DEBUG_NODE(the);
        }

        rule<Iterator, Skipper> story, the;
    };

    template <typename It>
        bool do_parse(It begin, It end)
    {
        bug_demo<It, space_type> grammar;
        return phrase_parse(begin, end, grammar, space);
    }
}

int main()
{
    std::cout << "Spirit version: " << std::hex << SPIRIT_VERSION << std::endl;

    try
    {
        std::string contents = "the lazy cow";
        if (do_parse(contents.begin(), contents.end()))
            return 0;
    } catch (std::exception e)
    {
        std::cerr << "exception: " << e.what() << std::endl;
    }
    return 255;
}
Run Code Online (Sandbox Code Playgroud)

我已经测试了这个

  • g ++ 4.4,4.5,4.6和
  • 提升版本1.42(ubuntu meerkat)和1.46.1.1(natty)

输出是

sehe@meerkat:/tmp$ ./bug 
Spirit version: 2020
Segmentation fault
Run Code Online (Sandbox Code Playgroud)

或者,使用boost 1.46.1会报告 Spirit version: 2042

hka*_*ser 5

按照答案中的建议更改初始化顺序只会隐藏问题.实际问题是,它rule<>具有正确的C++复制语义.您可以通过将gramar初始化重写为:

bug_demo() : 
    grammar<Iterator, Skipper>(story, "bug"),
    story(the.alias()),
    the("the")
{}
Run Code Online (Sandbox Code Playgroud)

有关基本原理和更详细的说明,请参见此处.