初始化const成员变量 [英] Initialize const member variables

查看:115
本文介绍了初始化const成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有C ++代码,可以归结为如下:

I have C++ code that boils down to something like the following:

class Foo{
    bool bar;
    bool baz;
    Foo(const void*);
};
Foo::Foo(const void* ptr){
    const struct my_struct* s = complex_method(ptr);
    bar = calculate_bar(s);
    baz = calculate_baz(s);
}

语义上,bar和baz成员变量应该是const,初始化后更改。然而,似乎为了使它们这样,我需要在初始化列表中初始化它们,而不是分配它们。要明确,我明白为什么 我需要这样做。问题是,我似乎没有找到任何方法将代码转换为初始化列表,而不执行以下不良事件之一:

Semantically, the bar and baz member variables should be const, since they should not change after initialization. However, it seems that in order to make them so, I would need to initialize them in an initialization list rather than assign them. To be clear, I understand why I need to do this. The problem is, I can't seem to find any way to convert the code into an initialization list without doing one of the following undesirable things:


  • 调用 complex_method 两次(对性能不利)

  • 添加指向Foo类的指针大)

  • Call complex_method twice (would be bad for performance)
  • Add the pointer to the Foo class (would make the class size needlessly large)

有没有办法使变量保持常量同时避免这些不良情况?

Is there any way to make the variables const while avoiding these undesirable situations?

推荐答案

如果你能买得起C ++ 11编译器,考虑 委托构造函数

If you can afford a C++11 compiler, consider delegating constructors:

class Foo
{
    // ...
    bool const bar;
    bool const baz;
    Foo(void const*);
    // ...
    Foo(my_struct const* s); // Possibly private
};

Foo::Foo(void const* ptr)
    : Foo{complex_method(ptr)}
{
}

// ...

Foo::Foo(my_struct const* s)
    : bar{calculate_bar(s)}
    , baz{calculate_baz(s)}
{
}

作为一般建议,请谨慎声明您的数据成员为 const ,因为这使得你的类不可能copy-assign和move-assign。如果你的类应该使用价值语义,这些操作变得可取。如果不是这样,您可以忽略此备注。

As a general advice, be careful declaring your data members as const, because this makes your class impossible to copy-assign and move-assign. If your class is supposed to be used with value semantics, those operations become desirable. If that's not the case, you can disregard this note.

这篇关于初始化const成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆