简体   繁体   中英

c++ Constructor member initialization : pass arguments

In my class I have private member variable 's3_client' as shown in the following code snippet

class GpuMatcher
{
private:
    Aws::SDKOptions options;
    Aws::S3::S3Client s3_client;
    ..
public:
    GpuMatcher();
    ..   
};

To configure 's3_client' I need to create some other dependent objects as follows :

Aws::Client::ClientConfiguration config;
std::string region=AppContext::getProperty("region");
Aws::String aws_region(region.c_str(), region.size());
config.region=aws_region;

Aws::S3::S3Client s3_client(config); //initialize s3_client

My question is, how can I initialize this in the class constructor ?

GpuMatcher::GpuMatcher() : options() , s3_client(???) 
{

}

If you need to pass arguments to this and also store the configuration (perhaps?):

class GpuMatcher
{
private:
    Aws::SDKOptions options;
    Aws::Client::ClientConfiguration config;
    Aws::S3::S3Client s3_client;

    static const Aws::Client::ClientConfiguration& populate_region(Aws::Client::ClientConfiguration& config);
    ..
public:
    GpuMatcher();
    ..   
};

and then:

GpuMatcher::GpuMatcher() : options() , s3_client(populate_region(config)) 
{
}

Be aware of the order here, as the config must be created before the client.

If you don't need to store the config (if it's a pass-by-value for the constructor), no need to pass in config to populate_region (and then it's a create_config ).

Make a function to generate the config object. eg

class GpuMatcher
{
    ...
private:
    static Aws::Client::ClientConfiguration generateConfig() {
        Aws::Client::ClientConfiguration config;
        std::string region=AppContext::getProperty("region");
        Aws::String aws_region(region.c_str(), region.size());
        config.region=aws_region;
        return config;
    }   
};

then

GpuMatcher::GpuMatcher() : options() , s3_client(generateConfig()) 
{

}

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