Friday, 30 September 2016

Office Best Practices - Expenses & Purchasing System

After taking a stroll through these pages, you may tell that I once commanded quite a large IT budget, in quite a large company.  I worked throughout the UK, into North Africa and out across Eastern Europe with them... There were Four levels of expenses in that organisation:


  1. Capitol Expenses (> £10,000)
  2. Red Band Expenses (<£10,000)
  3. Blue Band Expenses (< £1,000)
  4. Green Band Expenses (< £50)

Each department had a cost code, and various levels of staff were able to order on various levels of expense.  This worked brilliantly, lets go through a couple of examples:

Billy in stores needs a new roll of tape for boxing up equipment, he gets out his Green Band expenses sheet, fills it out, hands it to accounts payable, whom check Billy can use Green Band, which he can, he is listed.  They pass the purchase order to purchasing, and the item arrives at Goods In, and is taken to Billy.

Perfect for small items, it lets routine business be carried out, without fuss, you have accountability, and you don't need a senior; highly paid; person taking time out of their day to check and sign every little order, there is a cap limit on an order, and only certain people are assigned the location, and there are two points at which these orders are checked & summed, accounts payable and purchasing.  If there is any "fiddling" going on, both those points can independently check the other, and both check poor old Billy is not getting a kick back on the company.

Purchasing can also try to seek the best price, and accounts payable can handle taxes and other considerations.  At any point these orders could be sent back, for example, one system I personally worked to implement was a link between accounts & purchasing to the stores database (a FoxPro database at the time - yeah, you remember that!!) and it let them query if anything they were about to order was in stock!  Simple, and for my time it saved the company about £8,500 a year in sundry purchases as we stopped being up to the ears in paper clips, biro's and printer paper!

The other various levels of expenses in this system did need other security measures, so on Blue band, which is where I started as a member of staff, you needed to get a managers signature.  There being three levels of managerial staffing:

  1. Managing Director/CEO
  2. Director
  3. Manager
Each manager had between six and thirty people working for them, each director had between two and five managers, and there was one guy at the top... Well one woman at times, to be honest, and she was better... Any how...

So, a blue band raised by me, went to my manager, then was ordered....

A, Red band, raised by me went to my manager or he raised it, went to a director and was  triple checked.  Very rare were these, so people often knew they were coming, and they were planned for and adhered to the strict budgets in the accounts department.  Us lowly minions ordering the stuff, we put out business case on the form, people knew what was being talked about, and so we knew what was happening, we knew whether someone was just lining their nest with kit, or whether there was a genuine business need.

And when this very business was in trouble and being bought out by a rival in the US, we saw these requests drop and drop, the budget fall and fall, it was easy to understand where the company stood, where everyone stood.  It aided transparency, which made the staff; even in the face of the company being taken over; feel assured there was a plan, and someone was in control.

Finally, a Capitol Expense, I only saw these twice, when I had to buy a company car contract for myself... I loved that Audi... And then when we actually purchased a building, yes a whole building.

They went to the top, were discussed a lot, and got the job done.

This layering, might today seem strange, but I bring it all up, as a history lesson.  This system worked, it wasn't perfect, but it was regulated, it was transparent, it was not based on whom liked whom, or who knew who, it was based on a form, going through a process and getting a result.

Exactly the sort of thing a computer is very good at, and all this today could forego the forms and be an online purchase request system for a company, you log on, you put green's straight through, you put blues to an assigned manager... etc.

So, why the history lesson?  Because today, I've sat for four hours, with not one but two broken HDMI to DVI leads, both my main lead and the spare were broken, and broken in the same way.  I suspect the spare had actually been taken by someone else and their faulty one left in it's place in my cabinet.  But whatever the reason, I had two faults, and two machines down and sat struggling without the target platforms I'm deploying to.

No-one else in the company had any cables of this type, they all generally just use VGA, I'm the exotic one with DVI and HDMI.

So I go to find my boss to ask for cables, I work directly for the Director of Technology, he's a busy man, he's an expensive man to employ I'm sure, so why should he take time out of his day not only to listen to my needing cables, but to carry out the ordering himself?

It beggars belief, he has to find the item he wants me to have, not the item I prefer or have identified, he picks what he wants me to have, he raises the purchase order and he places the order, letting accounts know later.  Then the item may, or may not, come straight to me, it may sit in goods in until I gee them along and ask where the cables are.  Or it may just get sent straight to the very busy Director himself and it'll sit until he has time in his very busy day to open it.

The net result?... Delays and confusion.  The system is a black box.  I believe the idea behind this is that ordering things is seen as an expense, and the ability to order something within the company is seen as a traditional expensive thing.  This maybe because this is a nearly 55 year old company, and they're stuck in very old fashioned attitudes.

There is no need for this cloak and dagger approach, security through obscurity may leave those at the top of the chain feeling secure, but it leaves those of us trying to get the job done stuff waiting.  During the time we sit waiting, I've pondered the risk to reward for the company...

Now, not wanting to let out how much I earn, but lets just say the costs of the items I've needed over the last fortnight would total about two hours of my paid working hours.  How many hours have I spent waiting, stuck, not able to work whilst the kit was ordered by one busy person?... Five.

This is not the "how long to wait for the delivery", this is not "how long to get purchasing to order them", this was just how many hours from my raising the request with the busy Director and his actioning looking for the items and then letting me know they'd been purchased; he in fact didn't let me know, so I just take the difference in time between the end of the first day and the next when I had the mail confirming the order CC'd to me.

Five hours, versus two hours, meaning, if the company accepted, developed or adopted a Green Band expenses policy like the one above, almost tantamount to what might have once been called "petty cash" then they'd save money.

But of course no-one is looking at this holistically, they look at the price of the item, the amount of cash you could be spending on ordering items, and they see a LARGE chunk of money.  The company credit could rack up a lot of items on an order, and they'd be accepted by the suppliers because we're in good standing; and I understand this, I understand the need to secure that process or ordering.  That security should be the responsibility of accounts and purchasing, not the Director of Technology, and not me.

For you see, as much as the cost of ordering items tallies up for the company, and the accounts show that easily, less easily expressed is the cost of an hours time on a salaried worker.  We are a fixed cost, and probably less than the total purchasing power of the whole company.  So it gets ignored as a non-cost.  To leave me sat here waiting costs nothing extra.

Of course however, it does, it leaves me wondering about topics like this, about how the process works, about why I'm locked out of this trivial ordering task; when I used to command huge budgets, why am I not trusted to order a cable now (and I've worked here for a very long time); and if I'm not trusted, am I considered expendable, am I considered a joke.

It's the simple self-analysis of Office Paranoia, and it all begins because of a lack of transparency in ordering, and a lack of forethought as to how much it costs to "risk" letting people order trivial, petty, items as opposed to having an expensively paid Director be comptroller of order slips.

Monday, 26 September 2016

Story Time : Fantastic Rack Mount Mistakes #4

The final story in my little series, really revolves around the dread of all server room administrators... More nerve shredding than fire!  More nerve tingling than granting terminal access!.... We are of course talking about moving server room....

The plan was eeked out of management in literally, fifteen minutes of a meeting... We had three 6' racks all the wiring, all 2U servers in one rack with a 32 port switch at the top, nicely wired by good self (wishes I had a picture, but we were still using film for photo's back then, and it was too much effort).

The middle rack was a bit more the experimental kit, there was a 4U server in there, a couple of desktop cased machines stood directly on top of that unit - with plastic cutouts to stop hot air from the back feeding back to the front of the rack - yes, even with ghetto server layouts forced upon me, I did try to make the best of things and keep good order...

The third rack was telecomms units, it contained a bank of modems (yes, 64K modems!) another ethernet switch, an unmanaged switch too, and our SAN.

The SAN was a Dell EquiLogic; from memory I remember having 16 drives in it of 120Gb each, and two were hot spares...

The plan, from management, "unplug it all, load it into the two Nissan Primera Estate company cars, and move it from Derbyshire to Leicestershire"... 

That was it, "unplug and move"!

We had two days, over a weekend, to do this... It was Thursday afternoon... The clock was on.

Before you ask, I can't tell you much about why we had to move, nor whom I was working for, but let us just say, a week after the move the company changed name, and I changed employment soon after.

So, Thursday afternoon, I sent out e-mail to everyone, all staff, literally everyone, and said "The Servers are ALL going off, the Network is coming down, ALL IT services will be suspended at 3pm the following day".

Of course the whole place started to moan, so I promptly sent another mail.. "No seriously, ALL Services will be offline at 3pm, I'm serious!"  And I left the building to go see this new site... Two hours driving later, it's nearing 5pm Thursday and I arrive at a tin-shack looking warehouse like building, am let in by a man with a carrier bag and a cough.  I get the keys off of him to, and go check out the "IT Room" as he calls it.

It's a desk, with a single 15amp 240v rail supply and a bunch of cut off ethernet cables spilling out the wall in one corner.

There is no aircon, there is no patch panel, there is no racking... And it's on the first floor... (If you're from the US and reading this, here in the UK the floor against the ground is called "the ground floor", and the "first floor" is above that, it is up at least one flight of stairs... Yep, stairs... No lift (elevator).

Company credit card out, I head back to the office, and I order on next day (before 11am) delivery two RJ45 crimpers, two spools of ethernet cable, a pair of wall mountable 8U cabinets and a laptop (you know, because I thought I might need one) and a pair of walkie-talkies.

I then survey the kit I have to move, now, I can ignore the modems in the large, they unplug and lift out, but there's no telecomms due at the other end for a fortnight, so they'll go dark, they can be the last thing we move.  The switches in that right hand rack though therefore become free, and I can take them our now and start to set up the ethernet at the other end.

I have been assigned a minion from the shop floor to help, Friday morning comes and I await until 1pm that afternoon for my "before 11am delivery"... things are going so swimmingly already.  But I have had time to take the two desktop form factor servers offline, the 4U unit off line, the front blanking all out and disassemble the middle rack.  I've also got the switches from the right hand telecoms cabinet...

In our first transfer load we therefore have the rack, cables, UPS's, a 1U fold out terminal and crimpers in one car.  The two desktop servers and the 4U unit in the other.  We drive to the new site, unload the servers onto a trolley and lift them up stairs, placing them in a corner on the floor.

We then pull up the rack, assemble it, and fit a switch to the top of the cabinet and I send my helper off to survey the site, looking for any and all RJ45 sockets, and noting where they are, room by room and any notes on them.  I meanwhile start to splice new RJ45 connectors onto every one of the fifty or so ethernet cables laying on the floor, and I plug them into the switch.  I braid them all and cap them and wrap them nicely into the rack cable managements either side.

The switch has a useful line-test function, and my minion has the laptop!... So he can just plug a cable in at the other end and I see a light come on...  Over the radio I ask him to pick a socket, tell me if it's marked and to plug in... We do this room by room, and I move patches around to group rooms together, and I tell him a number to mark on the socket with a sharpie.

We've been at this mind numbing task for a couple of hours when I decide we need a break, and I go down to meet him... I'm a little aghast to see he's not written on the little window areas for the socket numbers, he's written them in letters as tall as the socket itself... *slaps forehead*.... It looks a mess, but it works, I'll have to come around in a weeks time with some acetone to clean it up, but it'll do... It'll do.

Fifty odd sockets later, we've got the whole building ethernet hooked into this switch.  The rack is powered and the UPS's are stable, reporting good, and the 4U server is up and fine from the laptop over a few of the sockets I've checked.

The two desktop servers survive the move too, and they're placed in the footing of the rack, rather then perched ontop.

Everything looks fab, and we've got this all done before 7pm on the Friday!  Things are looking GOOOODD!

I buy the chap helping me a pub meal, and he takes the company car home, I expect to see him Saturday morning.

Saturday morning, before switching down everything in the office, I check everyone is offline, and start to kill the servers down.  The SAN down, and pulling everything out of the rack, I'm stacking all the patch cables I'm taking all the units out and the car is pretty full.  Where is the other car?... 9am... 10am... No sign, I've got to call him.

He's at home, in bed... His wife describes him as, "Drunk as a lord"... He apparently didn't realise I needed him the next day, and had a skin full after he'd gone home.  He can't drive.

So, I'm flying solo... 

I drive the first load down to the new site, and basically throw it all out the back into the loading dock, and set off for the next load, I get the UPS's for this rack in the car and two of the 2U servers... and it's pretty much at load... Four more trips and I have all the servers at the new site, in the loading bay, and I'm taking the left hand rack down at the old place.

It won't come apart, and it's really a two man job... So, I give up, and I load all the bits I can up, and go to the new site, and decide to just stack the machines up off the floor but in a pile, rather then rack mounted, for a while.

So, machine by machine, I lug them up the stairs... It's heavy, it's hard, and I'm on the penultimate machine... When half way up the first flight of stairs I feel I'm about to loose my grip.

I try to catch a better hold, but it all happens at once, the machine is free, I'm toppling to my side as the weight takes me, and I'm going down the stairs on my side with my left finger in the thumb hook on the front of the server.

Lets just say, it was my left finger... And the server fell to my right.... Yeah, snappy snappy.

So, I have definitely broken my finger.  And I've definitely broken the server, as it bounced down about eight hard steps, the real flanges on the rack rails are all bent, the handles on the PSU units are smashed and the drives have shook loose...

Swearing and hobbling I crawl over to the machine, pop the lid and it's all fucked, just properly fucked.  The motherboard has popped up, everything is a mess.... That's an expensive mistake, but not-one I've ever admitted to, until now.

My finger however, needs attention, so I lock up and take a trip to A&E... After three hours they basically say it's a bad break, and put my hand in a mini-cast across the back of my hand and down my finger itself its all fixed.  I can use my wrist.

I return to the site, and luckily for me, there are no more servers to be lifted upstairs... Because someone has hiked open the loading dock roller door and pinched the one remaining server which was sat there.... They've also taken the laptop from upstairs, the two desktop profile servers and a bunch of other stuff...

When I go talk to the "security" guy, the old geeza with the bag from the previous day, he's still carrying his bag... I ask if he saw anything, "yeah saw one of your lads moving your computer things"... I explain he wasn't one of our lads... "I thought that funny, he didn't lift the roller, but crawled under it"... Total retard.

A 999 call later, and checking the grey CCTV, the policeman says he reckons he knows where our stuff is, and they set off to a well known local toe-rags house, where they find the shit with several 2U servers, a spool of ethernet cable and they're busy trying to log into my locked laptop, which was running OpenSuse and totally baffled them.

The police seize everything, I can't get the job done, I call the boss and tell him, and basically tell the security guy to not let a soul past him until they show the ID's for the company. 

Monday morning and I'm at the old site, showing people how to unplug their machines for transit to the new site, there's a fleet of vans to help now... You know, gotta move the leather chairs of the directors and the coffee machine properly, but the servers... ner just chuck them in the back of the car!

Needless to say, the ethernet all worked for everyone, replacement servers were easy enough to sort, and restore from the SAN, which was all fine and in place.  The smashed server was harder to explain, and I chose not to, and let everyone assume the thieves had dropped it, whomever dropped it, it was well insured, and the replacement was the first of the then new Dell Poweredge's with the Itanium 2 in them!

But, I soon left this role, the company was sold to a larger parent and stripped of assets.

The drunk, he had my eternal ire after doing such a good job initially I found him not so appealing.

The local toe-rag, got 3 months, all the assets took, IIRC seven weeks to be returned to us, and some bright spark had used aluminium dust to take finger prints off of them... JOYEOUS!

Friday, 23 September 2016

Reading my Reddit Comments (4001 CPU)

I've recently noticed spells when these pages come up with lots of hits from other sources, by far the most common is google, however, just now and then reddit becomes a source of my views, so I decided to take a look... I was happy, surprise and interested to see the threads... Lets take a look.


By far the most common of my posts to appear in reddit threads are tutorials, an interesting one, at least to me, is my 4001 CPU post.  Of course it is a miss-noma for me to call it the 4001 a CPU... The intel 4001 was a ROM chip, the 4004 was the CPU in that series; strangely no-one spotted that intentional change, and I had thought they would.


Click here for the original post on this blog.

The post is about re-creating an integer CPU in code, it was a forerunner to a series for instructing a class, the next posts, which were planned were to include floating point mathematics, however, the whole series was put on hiatus, and I never returned to the topic.

ninereeds314 on reddit calls me out on this, about my commenting that about 486SX code, where I said: 

"I know this because I once got told off for designing code with my 486SX2 processor - which could only add and subtract in hardware"

He says:

"No - even 8086 had integer multiply and divide instructions. They were slow enough that it was often worth avoiding them and using shift instructions and similar tricks if you could, and they could only work with the AX and DX registers (e.g. for multiply, AX x Source -> DX:AX) but they were there.
The 80386 32-bit versions of DIV, IDIV, MUL and IMUL were very similar, but working with EAX and EDX rather than just AX and DX where appropriate.
It was mostly the 8-bit chips that didn't have integer multiply and divide instructions. IIRC the Motorola 6809 was one of few 8-bit chips to actually have them, but came too late for the peak of 8-bit home computers - I think the best known machine it was used in was the Dragon 32.
Other than that, probably early RISC chips didn't have built-in multiply and divide instructions. One of the principles for RISC (at least years ago) was that every instruction should complete in one cycle, but multiply and divide needed a lot of transistors to do that - in practice they used microcoded algorithms (which was why they were slow)."
He is perfectly correct, my passing comment is slightly out of context, the 486SX could do integer multiplication and division as he says, it could not do floating point however, as it had a defective FPU which they disabled in the factory.  This was what the SX was, a crippled DX, which Intel remarketed as a cheaper chip, rather than throw away.
My article however is about 8-bit code, and I wasn't clear, the 4004 could NOT do direct multiplication of integers, it performed the multiplication by looping, as I had done in my code for the 486SX.  My solution for my code was quicker on the 486SX, which could do the integer add very quickly, but the multiplications were somewhat slower, over 100,000's of calls this did add up, so I avoided it; and in the article I'm only talking about an 8bit integer CPU.  I wasn't clear enough.

However, choralone, comments directly after and spots what I meant, so I know I'm not completely lost.

This discussion continues between ninereeds, choralone and nerd4code, as they discuss more deeply what I'm describing, and indeed I see ninereeds explain that the x87 co-processors, were slower; here he's wrong, once the data was delivered across the FSB to the co-processor they were extremely fast, unfortunately the gated way in which data was shuffled to the cache on the co-processors meant that they were slower, they also only generally ran at 12Mhz, so processing on them compared to a 286 itself was fast, shuffling data to and from them, was quite slow.  As it held the whole bus, with interrupts disabled.

The 387 co-processor was quicker, but could not use a 32bit bus, hence the 486 was designed to have the co-processor (redubbed an FPU) built in, but Intel had fabrication issues, and the photo-lithography techniques of the day left a lot of chips with perfectly functional integer cores, whilst the FPU's were defective... The answer, they severed the link to the FPU, relabelled it the SX and you had an emulating software library call, which vastly slowed the 486SX series down.

About this thread of discussion, I only wished they'd have had it on my actual blog... We like-minded people could have made firm friends!

On the same thread, we spin forward and the user "immibis" picks out my comment about where historically CPU's pick up their first instruction upon power on... he says he finds it hard to believe that they would pick a location in memory.

Well, they did, if a CPU picked 0x00 as it's start point, often it was not clear whether the CPU was reset, just powered, whether all the chips were ready, or the sync signal or whatever technology they had was ready, so it was common practice to have a all lines held low, and then raise on high along with the clock to indicate the start point of the CPU when it was literally first powered on, this high-line in early implementations (and indeed solid state machines before their being silicon) meant they didn't address zero, they in fact addresses a higher part of memory.... 0x800 was a common location for some machines I programmes for early on in my career.

Sometimes, as "jslepicka" points out, it was because the start of the address space was ROM, so the first instruction for execution was in ROM at memory address 2048, the preceding 2047 bytes had library calls, system calls and interrupt handling code in them.  And they were (sometimes) in physically different ROM chips, which could and would be swapped on development machines or embedded devices, so you could upgrade the system calls, patches to calls in these early 2047 bytes often turned into JUMP instructions out to new patches in higher areas of memory beyond the start, and then a series of NO-OP instructions to stop them being used.

However, some early machines had all the RAM at the start, and the ROM on a different address space, so you had to pull a line high to get to ROM over RAM (or vice versa), so you had two different memory spaces to address.  In those systems, you often had the problem that they were dodgy, memory was pretty daggy stuff, and chip failure rate high.

So, common practice, was to skip the first memory RAM chip at boot up, and use the second or third chips, according to the physical wiring diagram.  So the first chip, which would for a matter of pico seconds (or nano seconds, or however long the electricity took to start to flow) have an "over current" or jolt, was NOT being used.  As they genuinely tended to go bad more often, so much so it became routine for vendors, like Digital, to provide a book on how to actually make (with a soldering iron and logic chips!) your own replacement, or expansion memory!



There is also direct evidence of this in the books, of the skipping RAM and ROM, concepts... where you can still see references to the PWRUP functions, which established the power state (or power failure state) of AST (Async-System Trap) entry point addresses.  These AST entry point addresses were never ever 0x00, because... well that's just all the lines pulled low, i.e. no-power, and not indicative of the power being on, or off or in any state really.

Of course, I reference things from way before the PC era, when computers still came with manuals on the actual logic gates within...


Thanks to AlexeyBrin for posting my blog to Reddit, and thanks to all those whom commented, I had fun reading this one.

Thursday, 22 September 2016

Great British Bake Off... All Hands to the Pumps!

With the bake off heading over to Channel 4, it's been interesting to see one of the most talked about programmes in our office be re-discussed... It's also extremely interesting to get the inside track on some things, since I work with an Bake-Off contestant... Jordon Cox


So this morning, as we stood in the kitchen getting our coffee talking Networking issues, it was very interesting to see his reaction of non-surprise that Mary Berry would be staying with the BBC rather than going over to Channel 4.

We can all guess she was offered a large slice of the millions Channel 4 are going to be paying for the show, but what did Channel 4 think they were paying for?... TGBBO is a format, the music, the set design, the title, the sections, the format is the concept Channel 4 are paying for.  Indeed it was a little farcical recently when Jordon here appeared on BBC Radio Nottingham, but they couldn't play the theme tune to the show as the BBC don't have the rights.

But were Channel 4 paying for this format, for the crew of camera, set and sound operatives of so many shapes and sizes?... Or where they bidding for the whole package, where they bidding for Mel & Sue, with Mary & Paul?  I think they were.

I think there may very well be some squeaky bums over at Channel 4 towers right now, as they realise that not only have they potentially ruined the show, but that the millions whom will be tuned into slate the very hard acts to follow.

Paul Hollywood has, as yet, to comment on his position.  Jordon assures me he's not as dour as he is portrayed in the shows editing, he's a quite bright, funny guy.... I of course know this, not for his cakes or bread, but for his excellent taste in dogs (Labradors)... I'd like to think his announcement has not come because he will stick with the Beeb, and he has allowed, in his gentlemanly way, ladies to go first.  But he may just be wasting the cash register light up as more dough is coughed up for his approval and perhaps the last shred of a link to what was "The Great British Bake Off".


Addendum: Nope, seems Paul went with the Money... Humpf, gallantry is not in the pantry.

Monday, 19 September 2016

Dell Poweredge 2950 Perc 5/i RAID Controller RAM Fixes

Over the last few weeks you will have seen that I've been tinkering with my Dell Poweredge servers, I asked Morten over at "My Playhouse", his suggestion was that the RAID controllers should appear in the POST screens even if they had no RAM.

Mine were not appearing, however, whilst investigating Mortens suggestion I did try a different stick of RAM in one of the controllers, and it showed up!... The Dell Perc 5/i controller output light blue/cyan coloured text when it had an issue.

So, I did a lot of reading, and it's few and far between about exactly what RAM the controller should take... As I had HP marked RAM in a Dell RAID controller, it was clear somewhere in it's life this stick I have had been swapped out.

I read that I needed EEC DDR2 PC3200-R 333mhz RAM for the controller, and specifically they needed to be Rx8 or Rx16 types.

Luckily I recently had a donation directly to the blog, so I invested that kind gift into two second-hand sticks of RAM for the RAID controller... Here is the result:



Saturday, 17 September 2016

Tuesday, 13 September 2016

Software Engineering : C++14 Factory Create Pattern

For the GCC version of this, see this post (at the time of writing this link is to a scheduled item, it may not work just yet, scheduled for Tuesday 4th October 2016 at 18:30 GMT+1).

I commonly employ a "Factory Create" style to my classes in C++, the reason being I like to take control over the specific way that classes can be created, rather than relying on the compiler to always create the default constructors for me.  I like the constructors, but it leads to the problem of memory leaks, lets take a look at a bad example:


With this class any programmer can then do:

Alpha* l_somevalue = new Alpha(42);

They can then forget to call "delete l_somevalue;" and therefore leak memory.

We would therefore like to hide the constructors away, to prevent their miss use:


This necessitates we do expose someway to create an instance of the class, and that instance be wrapped as a smart pointer...


The first thing we see is a forward declaration of the class, then it's type wrapped as a smart pointer (a shared pointer in this case).  Next we see the various constructors have been made public, curing and removing all possibility of the programmer leaving hanging pointers to instances of our class.

Finally, we see a set of static "create" functions, our method to create an instance of the class now would look like this:

BetaPtr l_instance = Beta::Create();

When the reference count to the l_instance copy drops to zero then it will be automatically cleaned up, this is the whole point of this programming pattern.

There is nothing wrong with this code at the moment, we can define the constructors, knowing they can't be used outside the class, like this:


And the create functions look like this:


So far, we've learned nothing new... So what is new?... Well in C++14, really we should not be calling "new" at all.  The moment we see new outside the class we should implement this whole code pattern to hide the constructors away, exposing only smart pointers.  And likewise internally to those create functions we should not be calling "new", we should be using "std::make_shared".

Like this:


The problem?...


Hmmm... "error C2248: 'Beta::Beta': cannot access private memory declared in class 'Beta'", what is this telling us?

That the constructor of Beta could not access one of the private members of itself?  Huh?.. That makes no sense, of course the constructor should be able to access its own member!

What else does the error tell us?  "File: memory"... memory?... Not my code file, but the memory header?  We can open that location and take a look, what is the location of the error representing?


The _Ref_count_obj, the actual location that a shared_ptr is instantiated and the forward passed the arguments to the constructor, so the error is NOT that the constructor of our class can't get at it's private member, but that the template wrapped reference count object, which we inherit from because of the use of "make_shared", that reference can't get at the private members of the class!

How to solve this?... Simple:


Simply adding the "friend std::_Ref_count_obj<Beta>" allows that inherited class from "<memory>" to see inside the private area of the Beta class, and we enable the clean use of std::make_shared thereafter.

I highly recommend removing your constructors from prominence, and the use of "Factory Creation", as to other much more authoritative figures then myself.

My Complete code is below!

#include <iostream>
#include <memory>


class Alpha
{
private:

int m_AlphaValue;

public:

Alpha();
Alpha(const int& p_NewValue);
Alpha(const Alpha& p_OtherAlpha);

const int Value();
void Value(const int& p_NewValue);
};



class Beta;
using BetaPtr = std::shared_ptr<Beta>;
class Beta
{
private:

friend std::_Ref_count_obj<Beta>;

int m_AlphaValue;

Beta();
Beta(const int& p_NewValue);
Beta(const Beta& p_OtherBeta);

public:

static BetaPtr Create();
static BetaPtr Create(const int& p_NewValue);
static BetaPtr Create(const BetaPtr& p_OtherBeta);

const int Value();
void Value(const int& p_NewValue);
};


Beta::Beta()
:
m_AlphaValue(42)
{
}

Beta::Beta(const int& p_NewValue)
:
m_AlphaValue(p_NewValue)
{
}

Beta::Beta(const Beta& p_OtherBeta)
:
m_AlphaValue(p_OtherBeta.m_AlphaValue)
{
}

BetaPtr Beta::Create()
{
return std::make_shared<Beta>();
}

BetaPtr Beta::Create(const int& p_NewValue)
{
return std::make_shared<Beta>(p_NewValue);
}

BetaPtr Beta::Create(const BetaPtr& p_OtherBeta)
{
return std::make_shared<Beta>(*p_OtherBeta.get());
}




int main()
{
Alpha* l_Instance = new Alpha(42);
std::cout << "Alpha: " << l_Instance->Value() << std::endl;

BetaPtr l_BetterInstance = Beta::Create(42);
std::cout << "Beta: " << l_BetterInstance->Value() << std::endl;

// No need to delete l_BetterInstance, it cleans itself up

// Whoops... l_Instance of alpha leaks!
}