Search code examples
c++pointersboost-spirit

Are boost::spirit pointer attributes initialized with nullptr?


I think I saw in a debugger somewhere that a boost::spirit attribute of some pointer-type was set to nullptr, but I didn't do that. Was that just coincidence or does boost::spirit actually take care of initializing pointer-type attributes?

Currently I put an eps [ _val = nullptr ] at the start of a rule when I need to be sure, but it would be nice to know so I could omit that.


Solution

  • does boost::spirit actually take care of initializing pointer-type attributes?

    Effectively, yes.

    Spirit uses a make_attribute. The comment seems to indicate this would only happen for semantic actions, but it's actually also used inside the rule parser (but what gets passed to subparser expressions might be transformed).

    make_attribute uses the boost::value_initialized trait:

    Constructing and initializing objects in a generic way is difficult in C++. The problem is that there are several different rules that apply for initialization. Depending on the type, the value of a newly constructed object can be zero-initialized (logically 0), default-constructed (using the default constructor), or indeterminate. When writing generic code, this problem must be addressed. The template value_initialized provides a solution with consistent syntax for value initialization of scalar, union and class types. Moreover, value_initialized offers a workaround to various compiler issues regarding value-initialization. Furthermore, a const object, initialized_value is provided, to avoid repeating the type name when retrieving the value from a value_initialized object.

    So, barring any custom defined specializations in your code, the default behavior does offer value-initialization.