Initialize const member variables

后端 未结 4 1884
逝去的感伤
逝去的感伤 2021-01-01 11:47

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){
          


        
4条回答
  •  滥情空心
    2021-01-01 12:15

    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)}
    {
    }
    

    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.

提交回复
热议问题