Showing posts with label smart. Show all posts
Showing posts with label smart. Show all posts

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!
}

Tuesday, 16 August 2016

Programming : SDL_Window* into std::shared_ptr

I've had a little bit of a brain fart this morning, so to save you all the trouble, I'll go through it... First of all, I am working on an isolated system, therefore I had no internet, no clues, and importantly no books... This is a drag, because mainly I'll check things out look things up and just make sure I get things right... When things go wrong.

Unfortunately, things went wrong, and it was very early (for me) and I was unable to see the problem.

extern "C"
{
    #include <SDL.h>
}
SDL_Window* theWindow = SDL_CreateWindow (
    "The Window Title,
    SDL_WINDOWPOS_UNDEFINED,
    SDL_WINDOWPOS_UNDEFINED,
    800,
    600,
    SDL_WINDOW_SHOWN);

This code will create an SDL window at a unspecified location, with a size of 800x600 and the imaginative title "The Window Title".

This is fine, however, I hate seeing raw pointers, that "theWindow" variable irks me, it's just wrong to see that in modern C++ code; even if I am using a C based library.

So, I wanted to set about wrapping that into a smart pointer:

#include <memory>
namespace Xelous
{
    using SDLWindowPtr = std::shared_ptr<SDL_Window>;
}

This is my wanted type, "SDLWindowPtr", I know what this means to me, and I wanted to have a creating function wrap this for me:


The trouble?... This is considered an incomplete type, when we pass "SDL_CreateWindow" to the smart pointer ctor, it reports "incomplete type".


You can see the full error above, click to zoom in on the image.

So, what have I done wrong?... Well, the brain fart is to forget that "SDL_Window*" does not contain a standard destructor, it actually needs to be passed to SDL_DestroyWindow to close it down & release all resources.

I had totally forgotten this detail, I was too focussing too much upon the creation step and not thinking about the window objects life cycle.  The result was about 20 minutes wasted time banding my head wondering why this was happening.

Two cups of coffee and a pint of water, plus a wander down the corridor later, and I had that moment of realisation about this.


And so my code evolved, giving the solution to create a nullptr smart pointer result, then reset it to use the newly created window and instruct the smart pointer to use the SDL_DestroyWindow call for the clean up.

The complete code for a user might be more like this:

#include <string>
#include <memory>
extern "C"
{
    #include <SDL.h>
}

using SDLWindowPtr = std::shared_ptr<SDL_Window>;

SDLWindowPtr CreateWindowPtr (
    const std::string& p_Title,
    const unsigned int& p_X,
    const unsigned int& p_Y,
    const unsigned int& p_Width,
    const unsigned int& p_Height)
{
    auto l_result = SDLWindowPtr(nullptr);
    l_result.reset (
        SDL_CreateWindow(
            p_Title.c_str(),
            p_X,
            p_Y,
            p_Width,
            p_Height,
            SDL_WINDOW_SHOWN),
        SDL_DestroyWindow);
    return l_result;
}

int main ()
{
    SDLWindowPtr theWindow = CreateWindowPtr(
        "Hello World",
        10,
        10,
        800,
        600);

    SDL_Delay(5000);
}

We don't need to remember to SDL_DestroyWindow, we don't need to worry about forgetting to clean up, the smart pointer will do it for us when the reference count drops to zero.


Wednesday, 29 June 2016

Office of Tomorrow : Smart Pens

Making copious notes, meetings, diagrams, sketches... Today has been a day all about the pen, I'm one of the few developers around the place whom always has a pile of scrap paper and a bunch of coloured pens in order to express an idea.  Many of the projects I help with, or developers I point back into the right direction leave my desk with a lot of notes written out.

The trouble with this however, is I've just been tasked with finding a way to reduce the amount of paper going across everyone's desk, through the photocopiers and especially out of the printers.

I of course have no budget for this, being tasked with saving money means one is not actually able to speculate anything, even if it were in order to accumulate savings.

As such, I've discussed removing all flip charts for white boards, using apps on tablets, or smart phones (which seem ubiquitous around the place), and been thoroughly looked down upon.  Either by the owners of the devices steadfastly not wanting to use them for work purposes; which is fair; or their simply not wanting to stop using paper; which I agree with.

Unfortunately every scrap of paper used here has to go to a shredder, and as such we are paying for the paper, paying for the ink, paying for the time to put the ink on the paper, and then paying again to see it destroyed.

Those that be want something better, something digital, something progressive.

With drawing tablets already a taboo, and the insistence on not using their desktop PC's for such note making, I'm reducing the problem to something meeting three key criteria:

i) Reduce the paper usage in the long run, by digitising anything written down, and so removing the need for distributing physical copies... "Write Once, Share Forever".

ii) Leave users happy that they can still take, make, sketch or otherwise flesh out notes they take.  By hand, with a real pen.

iii) Not break the bank.

Having taken a look around, there is only one obvious candidate technology, the "Smart Pen".

This is a pen, designed to capture whatever they write from the real physical page, directly, to a digital page.  They do rely on apps, but some are generic bluetooth connected units, and so would be (I hope) fairly easy to connect to a desktop computer rather then a phone or tablet.

One can write once and indeed re-share that digital copy infinitely.

Unfortunately, the cost of entry to such ambrosia is very high, ranging from anything from £150 to £700.  

We shall have to see where this journey takes me, but certainly considering the technology of today which maybe more widely adopted, Smart Pens are high on my wish list, not least as information about them seems to sketchy.

Friday, 24 June 2016

Software Engineering : C++14/make_shared & Factory Create Pattern

I have a C++ issue, it's not often I can pick fault, but this is one of them... For years, I've used the factory create pattern; or at least my take on that pattern.  

Whereby I make the constructor private, or the whole class "Uncopyable/Uncreatable", and then I add a new static function which returns the class wrapped into a smart pointer.

By doing this, I get the advantage that no-one can use outdated "new" calls on it, and I drastically reduce the potential for third party memory leak creation/exploitation.

I can still do this with C++14, however, for a while now authors have recommended using "std::make_shared".  Their points are valid, but they break my factory creation pattern.  Which has much more to offer me than just using "make_shared" or whatever smart pointer creation template.

Lets take a look...


So, we have the class, but we're creating and deleting it in the old style, anyone forgetting to perform that delete will leak memory.


There, we can implement creating the class instance with a smart pointer...


A big change next however, we make the constructor private, to absolutely stop other programmers creating instances of our class with "new" and so totally negating anyone creating the class and potentially forgetting to delete it.

So we offer the programmer the static create function, which returns the shared pointer wrapped class... At least, that was the idea, as we can see, it utterly fails, because the std::make_shared template class is not a friend of our "foo" class.

Finally, we have to take a step back, to use the create, and hence enforcing our whole factory create pattern, we have to return this smart pointer wrapped instance after using "new".  This is fine, it is the same as "std::make_shared", but feels like a retrograde step.