returning handle to class internal data #effC++

Never quizzed in QQ, but how about BP? Might be a code smell.

Since c++ compiler is permissive and assumes you know what you wrote I believe it will compile.

Returning a handle (ref/ptr) to a class’s internal data is an everyday reality and inevitable, but tricky (– like online shopping) [[EffC++]] has a nice chapter /devoted/ to this topic. I don’t have the book now so here are my personal views.

Note — in contrast returning by value (pbclone) is safe.

java programmers feel safe to return “internal data”. I know from experience it’s seldom an issue. Therefore most of those c++ issues below are somehow “fixed” in java, largely because java is a simple_clean language, compared to the other 2 superpowers — C# and c++.

Issue: java immutable classes should not expose fields (except final primitives??). Ditto for c++, but more fine prints … C++ immutable is almost impossible. Constness can be cast away. A double-pointer field… (Java “final myField” means a field of either const-object or const-pointer to non-const object)

Issue: if an object is const or a method is const, then exposing that handle can break that “promise”. Apparently, c++ compiler can’t detect the “leak”. Java doesn’t make this kind of const “promise”

Issue: Once a handle is returned and “cached”, the original object had better (but often can’t) stay clear of the bulldozer, either on the stack or the heap. Fixed in java…(obviously)

Issue (java too): if a field is an integral and inseparable half of a pair which must be manipulated as a whole, then exposing the field alone is questionable. (Let’s not go into details) Any example?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s