Live data from Hacker News

C++ Patterns: The Badge

awesomekling.github.io

1–10 of 160 posts

Re: C++ Patterns: The Badge

#2
A different pattern I have thought of would be to provide an accessor interface object, and certain functionality is limited to be accessible only through that object. Controlling who has access to that interface can be flexible (possibly returning it along with construction, or passing it in at creation time...) Albeit, this is not without overhead, and for that, Badge is actually better, in terms of performance, if it fits the use case. What happens when you have multiple Device objects though, in this case, they can all access VFS..

--

C++'s private inheritance can be used here to avoid some of the gymnastics, wherein, that private aspect of the class can be passed out into the appropriate party at creation time or otherwise.

To illustrate: https://gist.github.com/arithma/0d96aec5c07e2d8dc24cfc6cd31f...

Note: I have never used this in production as far as I remember.

Re: C++ Patterns: The Badge

#8
I had never seen this before, I cannot think of another way to do this. I suspect it has 1 byte overhead (on the stack) cost, but that's pretty cheap and may be optimized out.

Re: C++ Patterns: The Badge

#9
post #7

I like it but is access restriction really a problem? In my years of C++ programming it always seemed to be a theoretical problem more than something that leads to crashes.

I'd guess it's more architectural concern than runtime. Making sure only code that is supposed to uses a semi-private interface so people don't build dependencies that aren't wanted.

Re: C++ Patterns: The Badge

#10
I do C++ for almost 20 years but never came across this simple technique before, so I'm quite surprised that I actually like it.

I usually avoid 'friend' in these situations and just write

    //private:
before the method declaration. But it actually happened that co-workers used these private methods because they use code-completion instead of reading the header...

But I might would call the class Friend or something.

Post reply on HN