Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing from a pair in constructur intializer list

I have a function f returning a pair of objects of classes A and B:

auto f() -> std::pair<A,B>;

Furthermore, I have a class C that has A and B as members:

class C {
  public:
    C();
  private:
    A a;
    B b;
};

In the constructor of C, I want to use the member initalizer list and initialize with the output of f:

C(): a(f().first), b(f().second) {}

This calls f twice though and it is a quite complicated function. Is there a way to achieve this using the member-initializer list without calling f twice? The internal structure of C can unfortunately not be changed.

like image 392
Henk Avatar asked Oct 18 '25 17:10

Henk


1 Answers

Improving on the idea from AnkitKumar's answer:

class C
{
    A a;
    B b;
    
    C(std::pair<A,B> &&pair) : a(std::move(pair.first)), b(std::move(pair.second)) {}

  public:
    C() : C(f()) {}
};
like image 103
HolyBlackCat Avatar answered Oct 20 '25 08:10

HolyBlackCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!