Hacker News new | ask | show | jobs
by gumby 2340 days ago
Here's a simple example: I have a table of stageful actions (perhaps part of a UI) that is dynamically constructed and maintained. I could register token which looks up the necessary information in an internal hash table. Of course said internal table would have to stay in sync with the UI's table. Instead I can just return an opaque object (perhaps a virtual object if life is fancy) with all the necessary state; if the UI window is deleted then all the objects will be deleted too at just the right time, with no explicit coordination with the part of code that created them (their destructors could do some bookkeeping if appropriate).

Traditional callbacks can also be used in this case, but what is a callback lambda but private state? And a stateful object rather than a lambda function is easier to manipulate, say by inspecting in the debugger or perhaps by providing a generic function for things like printing the entry.

Another case is where you have some hairball third party or legacy library that you want to be able to use in your modern code; you can often simply make it an opaque private object rather than making a complex visitor for it.

1 comments

I kind of understand what you describe, but I still don't understand why the type needs to be private. You can return opaque objects of a public type just as well for this job, can't you?

    class Token {
      virtual ~Token();
      protected:
        friend class MyClass;
        ...
        /* all your state */
    };
> what is a callback lambda but private state?

You can (and do) program to the callback's interface -- say you ask for an std::function<void()>, and the user gives you that. What is behind the function (private state or not) is not your concern, you simply perform an public operation (calling it) on a public interface (i.e., via std::function).

What is the difference to you if I pass a private object or a public object all of whose instance variables and methods are private? Either way the point is to say “this is not your object to manipulate”. But making it a type you cannot even express makes that far more explicit.
I see, I guess then that's where we disagree. It is very confusing for people from my limited experience, for little gain. Plus you make it harder to do things like put these tokens in e.g., a vector without resorting to decltype.

Going back to the original point i was making with this example, I still think this was probably not a capability consciously designed in the language.