Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ temporary variables in initialization list

Tags:

In C++, is there any way to have something like a temporary variable in an initialization list. I want to initialize two constant members with the same instance of something without having to pass that something in, remove the const requirement, use a Factory (i.e. pass it in but have the factory generate it to hide it from the API user), or have temp actually be a member variable.

I.e. something like

Class Baz{
    const Foo f;
    const Bar b;
    Baz(Paramaters p):temp(p),f(p,temp),b(p,temp){ //temp is an instance of Something
                                                  // But NOT A member of Baz
    // Whatever
    }
}

instead of

Class Baz{
    Foo f;
    Bar b;
    Baz(Paramaters p){
        Something temp(p);
        f = Foo(p,temp)
        b = Bar(p,temp)
    }
}

or

Class Baz{
    Foo f;
    Bar b;
    Baz(Paramaters p,Something s):f(p,s),b(p,s){
    }
}
like image 338
imichaelmiers Avatar asked Jun 28 '13 23:06

imichaelmiers


1 Answers

In C++11 you could use delegating constructors:

class Baz{
    const Foo f;
    const Bar b;
    Baz(Paramaters p) : Baz(p, temp(p)) { } // Delegates to a private constructor
                                            // that also accepts a Something
private:
    Baz(Paramaters p, Something const& temp): f(p,temp), b(p,temp) {
        // Whatever
    }
};
like image 125
Andy Prowl Avatar answered Sep 18 '22 21:09

Andy Prowl