Effective C++ 2.10, have assignments return reference to *this


#1

newbie question I didn't see covered elsewhere: seeing as Scott Meyers & Julian are BFFs now cheeky I assume there's a reason Juce doesn't return *this on most assignments - should this be coverered in the C++ style section?

thx,

-- p


#2

Scott is indeed a nice guy :)

But I do always return *this, don't I..? There will probably be exceptions to that rule for obscure reasons, but I had a quick scan through and couldn't see any classes at all which didn't do it like that! Which ones are you talking about?


#3

I guess stuff like Component::addAndMakeVisible() or var::append(), most assignment ops in these classes return void (those I saw anyway).

But you're right, looking at WindowsDemo.cpp I do see some chaining there, I probably don't have a wide enough picture yet.

thx!

-- p


#4

Oh, I thought you were talking about the actual assignment operator, i.e. operator=

I have done some chaining in places, but haven't got a strict rule for it, and there are some places where it's not *this that would be best to return, but rather an object that was passed in as an argument that would be most useful for chaining.

There are also some places where performance might be a consideration, since the compiler may not always be able to optimise-away an unused return value, and the fact that it returns a reference could mean that it's unable to use other optimisations for because it stops it making assumptions about the scope in which objects are visible. Obviously in some cases this doesn't matter, but in code that may be used in cpu-heavy areas it needs to be thought about.

But if you do spot some places where you think chaining would be useful, please let me know, because it's easy to add!


#5

I am guessing that when the returned *this isn't the one you'd want it's because of "subject inversion" (?). F.ex. one could turn

m_TextCtrl.setMultiLine(true);
m_TextCtrl.setReadOnly(true);
m_TextCtrl.setCaretVisible(false);
addAndMakeVisible(m_TextCtrl);

into

m_TextCtrl.setMultiLine(true).setReadOnly(true).setCaretVisible(false).addToComponent(this).setVisible(true);

but that looks too traumatic a change, hence unhelpful?

-- p


#6

Yeah, making things like setMultiline chainable is a nice idea. The addToComponent() idea might be a bit confusing though, and could be done in other ways anyway, e.g.

addAndMakeVisible (child.setMultiline (true).setReadOnly (true));

 


#7

Nice idea. Chaining like that can help readabilty and flow when coding. 


#8

For accuracy's sake I should withdraw the Scott Meyers reference since Method Chaining has nothing to do with"Effectice C++", except it returns *this.  Couldn't find its actual origin, Wikipedia says it's Smalltalk-inspired and sometimes called "a train wreck". Ahum.

-- p