簡體   English   中英

嵌套Boost :: variant的細分錯誤

[英]Segmentation fault for nested boost::variant

以下程序已從原始程序中刪除。 運行時出現細分錯誤。 如果我使用ArithmeticUnaryExpression刪除第24行,則程序不再崩潰。 如何擺脫細分錯誤?

#include <boost/config/warning_disable.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/variant.hpp>
#include <boost/spirit/include/qi_expect.hpp>
#include <boost/spirit/home/x3/directive/expect.hpp>

#include <iostream>
#include <string>

namespace wctl_parser {

namespace x3 = boost::spirit::x3;
namespace ascii = x3::ascii;
namespace qi = boost::spirit::qi;

using x3::ulong_;
using x3::lexeme;

//--- Ast structures
struct ArithmeticUnaryExpression;
using AtomicProp = std::string;

using ArithmeticExpression = x3::variant<
    x3::forward_ast<ArithmeticUnaryExpression>,
    unsigned long
>;

struct ArithmeticUnaryExpression {
    std::string op;
    ArithmeticExpression operand;
};

using Expression = x3::variant<
    ArithmeticExpression
>;

template <typename T> auto rule = [](const char* name = typeid(T).name()) {
    struct _{};
    return x3::rule<_, T> {name};
};

template <typename T> auto as = [](auto p) { return rule<T>() = p; };

//--- Rules

x3::rule<struct aTrivRule, ArithmeticExpression> aTriv("aTriv");
x3::rule<struct exprRule, Expression> expr("expression");

auto const aTriv_def = rule<ArithmeticExpression>("aTriv")
    = ulong_
//  | '(' > expr > ')'
    ;

auto const primitive = rule<Expression>("primitive")
    = aTriv
    ;

auto const expr_def
    = primitive
    ;

BOOST_SPIRIT_DEFINE(aTriv)
BOOST_SPIRIT_DEFINE(expr)

auto const entry = x3::skip(ascii::space) [expr];

} //End namespace

int main() {

    std::string str("prop");
    namespace x3 = boost::spirit::x3;   
    wctl_parser::Expression root;
    auto iter = str.begin();
    auto end = str.end();
    bool r = false;
    r = parse(iter, end, wctl_parser::entry, root);
    if (r) {
        std::cout << "Parses OK:" << std::endl << str << std::endl;
        if (iter != end) std::cout << "Partial match" << std::endl;
        std::cout << std::endl << "----------------------------\n";
    }
    else {
        std::cout << "!! Parsing failed:" << std::endl << str << std::endl << std::endl << "----------------------------\n";
    }
    return 0;
}

您的變體

using ArithmeticExpression = x3::variant<
    x3::forward_ast<ArithmeticUnaryExpression>,
    unsigned long
>;

將默認構造為第一個元素類型。 第一個元素類型包含ArithmeticExpression ,它也是默認構造的。 您已經看到問題了嗎?

只要確保默認構造狀態不會導致無限遞歸:

using ArithmeticExpression = x3::variant<
    unsigned long,
    x3::forward_ast<ArithmeticUnaryExpression>
>;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM