代码比lambda简单,在构造函数中使用一个输出参数函数初始化一个const成员 [英] Code simpler than lambda for a call in constructor that uses an output parameter function for initializing a const member
问题描述
在标题中,我有
class CSomeClass
{
const GUID m_guid;
public:
CSomeClass();
///...
}
/ p>
And in the source file
CSomeClass::CSomeClass()
, m_guid(
[]() {
GUID g;
::CoCreateGuid(&g);
return g;
}()
)
{
}
正如你所知道的Guids可以被用作标识,而不是要改变。给定 :: CocreateGuid()
函数提供了我想要的作为输出参数,而不是返回它,我不能直接使用一个简单的调用函数来初始化m_guid成员字段,即常数。
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.
所以,它的常量的一个结果是,它必须在初始化列表中的开始括号之前初始化,因此不能简单地分配一个 :: CocreateGuid()
在构造函数体中。
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.
有比这个lambda表达式更简单的方法来初始化它吗? p>
Is there a simpler way to initialize it than this lambda expression?
推荐答案
当lambda表达式正确时,我将使用一个辅助函数:
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()) {}
此外, 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).
这篇关于代码比lambda简单,在构造函数中使用一个输出参数函数初始化一个const成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!