Wednesday, 13 July 2016

c++ - Code simpler than lambda for a call in constructor that uses an output parameter function for initializing a const member



In the header, I have



class CSomeClass
{
const GUID m_guid;


public:
CSomeClass();
///...
}


And in the source file



CSomeClass::CSomeClass()

, m_guid(
[]() {
GUID g;
::CoCreateGuid(&g);
return g;
}()
)
{
}



As you know Guids can be used as identifications not meant to be changed. Given the ::CocreateGuid() function provides what I want as an output parameter, instead of returning it, I cannot use directly a simple call to the function for initializing the m_guid member field, that is constant.



So, a consequence of its constness, is that it must be initialized before the opening bracket in initializer list, and therefore not be simply assigned with a call to ::CocreateGuid() in the constructor body.



Is there a simpler way to initialize it than this lambda expression?


Answer



When the lambda expression is correct, I would use a helper function for that:



GUID create_guid()

{
GUID g;
::CoCreateGuid(&g);
return g;
}

CSomeClass::CSomeClass() : m_guid(create_guid()) {}


In addition, create_guid() has a meaning by itself and could be reused (even if making it a implementation detail is possible/correct).



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...