Search code examples
c++factoryconstruction

The ** idiom in C++ for object construction


In a lot of C++ API'S (COM-based ones spring to mind) that make something for you, the pointer to the object that is constructed is usually required as a ** pointer (and the function will construct and init it for you)

You usually see signatures like:

HRESULT createAnObject( int howbig, Object **objectYouWantMeToInitialize ) ;

-- but you seldom see the new object being passed as a return value.

Besides people wanting to see error codes, what is the reason for this? Is it better to use the ** pattern rather than a returned pointer for simpler operations such as:

wchar_t* getUnicode( const char* src ) ;

Or would this better be written as:

void getUnicode( const char* src, wchar_t** dst ) ;

The most important thing I can think of is to remember to free it, and the ** way, for some reason, tends to remind me that I have to deallocate it as well.


Solution

  • "Besides wanting error codes"?

    What makes you think there is a besides. Error codes are pretty much the one and only reason. The function needs some way to indicate failure. C doesn't have exceptions, so it has to do that through either a pointer parameter, or the return value, and the return value is idiomatic, and easier to check when calling the function.

    (By the way, there's no universal rule that ** means you have to free the object. That's not always the case, and it's probably a bad idea to use something that arbitrary to remind you of which objects to clean up.)