简体   繁体   中英

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
         //This loading is depend on the values of config
    };
    Engine(Configuration const& config):config(config){
         //Very have model loading from hard disk is occurs here
         //This loading is depend on the values of config
    }
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?

EDIT:

Someone may thought of simple solution that I should provide a setter method for the config in the engine class. So, I can just set it after loading. This is not an option because the loading process is depending on the config . So if I change the config I should reload again.

Just move the preparation of Configuration to a member function:

class foo{
public:
     foo() : eng(prepare_config()){
     }

     Configuration prepare_config() {
         Configuration config;
         config.a=5;
         config.b=5;
         //...
         config.z=5;
         return config;
     }
private:
     Engine eng;
}

Make sure you do not access any foo members in prepare_config() (or just make prepare_config() static).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM