构造函数主体中的对象初始化



我已经编写了一个类来根据模式执行存储在unordered_map中的数据的输出。我希望这个模式在创建时传递给对象,并且在对象生命周期内保持不变。

这是我第一次写的课:

class Format {
public:
  Format(const string output_pattern);
  string interpolate(const boost::unordered_map<string, string> & field_values);
private:
  ...
};

我想以这种方式在另一个类中使用Formatter

class A {
private:
  Format formatter;
public:
  A(const std::map<std::string, std::string> & info, ... other parameters) {
    std::map<std::string, std::string>::const_iterator it;
    it = info.find("format");
    if (it == info.end()) {
      throw std::runtime_error("Can't find 'format' in info");
    } else {
      formatter = Format(it->second);
    }
  }
};

正如您所看到的,在调用构造函数之前还有一些工作要做。毫无疑问,它不起作用,因为format首先是用默认构造函数初始化的(缺少默认构造函数),其次它需要为formatter = Format(it->second);行定义赋值运算符。

我不能像这样初始化formatter

A(const std::map<std::string, std::string> & info, ... other parameters):
  formatter(...) {
  ...
}

因为我必须首先提取要作为formatter初始值设定项传递的参数。

所以,最终我用这种方式解决了这个问题:

class Format {
public:
  Format();
  void set_pattern(const string output_pattern);
  string interpolate(const boost::unordered_map<string, string> & field_values);
private:
  ...
};

class A {
private:
  Format formatter;
public:
  A(const std::map<std::string, std::string> & info, ... other parameters):
    formatter()
 {
    std::map<std::string, std::string>::const_iterator it;
    it = info.find("format");
    if (it == info.end()) {
      throw std::runtime_error("Can't find 'format' in info");
    } else {
      formatter.set_pattern(it->second);
    }
  }
};

我真正不喜欢的是,这将不可变的formatter对象变成了可变的。这不是什么大问题。但我不需要它是可变的,也不喜欢因为它是不可变的,我不能用代码来表达它而必须使它可变。

在我的情况下,有没有其他好的方法可以在构造函数中初始化它?

您可以使用助手专用函数来完成实际工作:

class A {
private:
  SomethingA before;
  Format formatter;
  SomethingB after;
public:
  A(const std::map<std::string, std::string>& info) :
    formatter(extractFormat(info))
  {
    // ...
  }
private:
  string extractFormat(const std::map<std::string, std::string>& info)
  {
    // Be careful here! The object is not constructed yet, you can't fully use it
    // this->before => ok
    // this->after => not ok
    // you could make this function static just to be safe
  }
};

最新更新