Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intermediate calculations inside initialization list

Tags:

c++

I have something like

struct Foo {
    const double a;
    const double b;
    Foo(double c);
}

Foo::Foo(double c) {
    double tmp = f(c);
    a = g(tmp);
    b = h(tmp);
}

where f,g,h are functions implemented elsewhere. This gives the expected "uninitialized const member" error.

I could fix it with

Foo::Foo(double c): a (g(f(c))), b (h(f(c))) {}

but f is an expensive function and I wouldn't like to run it twice.

My question is, how can I solve this problem without running f twice or making tmp a permanent member of Foo?


1 Answers

Typically, delegating constructors offer a simple solution to this type of problem. In this case you'll have to introduce some way to distinguish between the two constructors:

private:
  // the int param is unused
  Foo(double fc, int) : a(g(fc)), b(h(fc)) {}

public:
  Foo(double c) : Foo(f(c), 0) {}
like image 164
Brian Bi Avatar answered Apr 10 '26 05:04

Brian Bi



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!