I have a templated class that is dependent on two template parameters to calculate its values but only one for construction. I would like to relieve the dependency on the second over its lifetime. I am looking at doing this by using a templated static function to calculate the values and then create an instance. All of the members inside this class are const POD types and there will be a good many of this class being created at application start up.
template < class member >
class FOO {
public:
FOO() : a(7) {};
template < class scope >
static FOO CreateFOO()
{
return FOO();
};
private:
const int a;
};
template < class member, class scope >
const FOO< member >* function()
{
static const FOO< member >& temp = FOO< member >::CreateFOO< scope >();
return &temp;
}
int main() {
const FOO<int>* b = function< int, int >();
return 0;
}
I contemplated move semantics but because I am simply containing const POD types there really isn’t any swapping and moving simply copying and destroying. Is the above reasonable/valid? Everything I have read suggests it is ok! Is there a better way to do this?
This should be okay. Since the reference
tempis bound to the temporary object, the lifetime of the temporary is extended to the lifetime oftemp, which extends past the end ofmain().But I don’t see any real reason to use a reference there. Why not just:
Your compiler can probably optimize away the copy constructor. And if not, you say it’s all POD members, so no big deal.
Either way, you might worry about the static deinitialization order fiasco. Or maybe you’re sure they’ll never be used from destructors.