C++ Logo

std-proposals

Advanced search

Re: Variables in constructor member initializer list

From: DBJ <dbj_at_[hidden]>
Date: Wed, 1 Sep 2021 12:32:36 +0200
Why not just use the factory method?

class MyClass {
     const int a, b, c;
     MyClass(int a_, int b_, int c_)
      : a(a_), b(b_), c(c_)
     { }
public:
static MyClass factory( int someBaseValue )
      {
          auto someDerivedValue = SomeHeavyOperation(someBaseValue);
          return MyClass{
              someDerivedValue * 2,
              someDerivedValue / 3,
              someDerivedValue + 4,
          };
      }
};

Bonus:

I do not know much about them, but the added benefit might be that the
factory can be a co-routine. A constructor can not be a co-routine.
Thus in that case SomeHeavyOperation() will not stop "everything".

On Wed, 1 Sept 2021 at 11:57, Edward Catmur via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On Wed, 1 Sept 2021 at 10:23, Artyom Lebedev via Std-Proposals <
> std-proposals_at_[hidden]> wrote:
>
>> You are right, I missed this feature. However, it is still a matter of
>> convenience. Besides passing list of parameters, you also need to ensure
>> the delegating constructor signature is not colliding with any other
>> constructor, requiring constructions like this:
>>
>> class MyClass {
>> public:
>> const int a, b, c;
>>
>> MyClass(int someBaseValue)
>> : MyClass(SomeHeavyOperation(someBaseValue), ConstructorTag())
>> {}
>>
>> private:
>> struct ConstructorTag {};
>>
>> MyClass(int someDerivedValue, ConstructorTag) :
>> a(someDerivedValue * 2),
>> b(someDerivedValue / 3),
>> c(someDerivedValue + 4)
>> {}
>> };
>>
>> or introducing dedicated structure for passing construction parameters
>> in, which is quite verbose.
>>
>> Introducing delegated constructors made much code less verbose.
>> Introducing variables in member initializer list could make the next
>> step to make it even neater.
>>
>
> It'd be enough if there were a way to re-enable aggregate initialization
> (maybe with private access) in the presence of constructors; then we could
> use an iife and named initialization:
>
> class MyClass {
> public:
> const int a, b, c;
>
> MyClass(int someBaseValue)
> : MyClass([&]
> {
> auto someDerivedValue = SomeHeavyOperation(someBaseValue);
> return MyClass{
> .a = someDerivedValue * 2,
> .b = someDerivedValue / 3,
> .c = someDerivedValue + 4,
> };
> }())
> {}
> };
>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2021-09-01 05:32:57