简体   繁体   中英

Use function call result to initialize multiple members in C++03?

I currently have a class where I need accomplish the equivalent of the following (I can't post my actual code):

class Data
{
public:
    Data(const std::string &data_string)
      : member_1(splitData(data_string)[0]),
        member_2(splitData(data_string)[1]),
        member_3(splitData(data_string)[2]),
        member_4(splitData(data_string)[3]),
        member_5(splitData(data_string)[4])
    {}
};

The problem is that splitData is expensive, and I would like to run it only once. Normally, I would store the result in a local variable in the body of the constructor, but, in this case, many of the members are not default constructible, so I have to initialize them in the initializer list.

I know in C++11 I could use delegating constructors to solve my problem:

class Data
{
public:
    Data(const std::string &data_string)
      : Data(splitData(data_string)) // splitData only called once
    {}
private:
    Data(const SplitResult &split_result)
      : member_1(split_result[0]),
        member_2(split_result[1]),
        member_3(split_result[2]),
        member_4(split_result[3]),
        member_5(split_result[4])
    {}
};

But I can't figure out any way to do it in C++03.

How about you make split_result a member you just use for initialization:

class Data
{
    SplitResult split_result;
    //declare member_x here
public:
    Data(const std::string &data_string)
      : split_result(splitData(data_string)),
        member_1(split_result[0]),
        member_2(split_result[1]),
        member_3(split_result[2]),
        member_4(split_result[3]),
        member_5(split_result[4])
    {}
};

Just make sure you declare it before the other members, so it is initialized first. Member initialization order is determined by the order in which they are defined in the class.

Data (const std::string data_string, 
          SplitResult split_result = split_data(data_string)) : 
    member_1(split_result[0]),
        ...

This is not checked, I'm on a mobile phone...

** UPD ** no it won't work. A new attempt:

Data (const std::string data_string, 
          SplitResult split_result = SplitResult()) :
    member_1((split_result = split_data(data_string))[0]),
    member_2(split_result[1]), 
        ...

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