jeudi 24 décembre 2015

Initialize member variable once in class

I have the following two classes:

class foo{
public:
     foo(){
         Configuration config;
         config.a=5;
         config.b=5;
         //...
         config.z=5;
         eng=Engine(config);
     }
private:
     Engine eng;
}

class Engine{
public:
    Engine(){
         //Very have model loading from hard disk is occurs here
    };
    Engine(Configuration config):config(config){
         //Very have model loading from hard disk is occurs here
    }
private:
    Configuration config;
}

It is obvious the way of initializing the eng member variable in foo constructor is very bad becuase eng has been initialized twice (which is very expensive). In order to solve this problem I made the eng as unique_ptr and initialized once in the foo constructor using std::make_unique:

class foo{
    public:
         foo(){
             Configuration config;
             config.a=5;
             config.b=5;
             //...
             config.z=5;
             eng=std::make_unique<Engine>(config);
         }
    private:
         std::unique_ptr<Engine> eng;
    }

This solved the problem of unnecessary initializing. However, I think that I have solved it in the wrong way. I can not see an obvious reason to use pointers. I think that there is a better solution with stack member variables.

The question is : Is it true that pointer-based solution should be avoided as much as possible? If yes, what is the best solution for my case?

Aucun commentaire:

Enregistrer un commentaire