Style guideline on initializing non-POD types via member initialization

# Simon Fraser (8 days ago)

I've seen some code recently that initializes non-POD members via initializers. For example, SVGAElement has:

AttributeOwnerProxy m_attributeOwnerProxy { *this };

I find this a little disorientating, and would normally expect to see this in the constructor as m_attributeOwnerProxy(*this), as it makes it easier to find places to set breakpoints, and the ordering of initialization is easier to see.

Are people OK with this pattern, or should we discourage it via the style guidelines (and style checker)?

Simon

Contact us to advertise here
# Filip Pizlo (8 days ago)

I like to draw this distinction: is the initializer a constant?

It’s not a constant if it relies on arguments to the constructor. “This” is an argument to the constructor.

It’s also not a constant if it involves reading the heap.

So, like you, I would want to see this code done in the constructor. But I’m not sure that my general rule is the same as everyone’s.

# Simon Fraser (2 days ago)

On Mar 14, 2019, at 1:06 PM, Filip Pizlo <fpizlo at apple.com> wrote:

I like to draw this distinction: is the initializer a constant?

It’s not a constant if it relies on arguments to the constructor. “This” is an argument to the constructor.

It’s also not a constant if it involves reading the heap.

So, like you, I would want to see this code done in the constructor. But I’m not sure that my general rule is the same as everyone’s.

This seems like a reasonable proposal to me: only use initializers when their input is constant data.

Any objections?

Simon

# Alex Christensen (16 hours ago)

I object. I don’t find using { *this } in a header disorienting at all. I think it’s better than adding many duplicate lines in each constructor and risking forgetting one. I think if we were to remove all the m_attributeOwnerProxy initializers in WebKit it would add lots of duplication with little benefit. If it were a class with a default constructor we would have a high risk of forgetting a constructor somewhere.

# Alex Christensen (15 hours ago)

A more specific example of why I object is that I want to do things like add a pointer to the thread an object was created on if ASSERT_DISABLED is false so I can assert if things are done on invalid threads. If I do this in a class like RefCounted, this rule would make me add a guarded initializer to every RefCounted class.

# Filip Pizlo (14 hours ago)

I don’t like style rules that prevent doing useful things, and this seems like a useful thing.

Want more features?

Request early access to our private beta of readable email premium.