Initialize const member variables

后端 未结 4 1854
逝去的感伤
逝去的感伤 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:04

    If you don't want to use the newfangled delegating constructors (I still have to deal with compiler versions that don't know about them), and you don't want to change the layout of your class, you could opt for a solution that replaces the constructor with const void * argument by a static member function returning Foo, while having a private constructor that takes the output from complex_method as argument (that latter much like the delegating constructor examples). The static member function then does the necessary preliminary computation involving complex_method, and ends with return Foo(s);. This does require that the class have an accessible copy constructor, even though its call (in the return statement) can most probably be elided.

提交回复
热议问题