在构造函数中初始化 const 字段

fac*_*iel 4 c++ constructor constants ctor-initializer

C++ 中的 const 字段必须在初始化列表中初始化,这使得从构造函数参数计算相互依赖的值变得非常重要。

例如,将这段 java 代码翻译成 c++ 的最佳方法是什么?

public class SomeObject {
  private final String some_string;
  private final int some_int;

  public SomeObject(final String input_filename){
    SomeReader reader(input_filename);

    some_string = reader.getString();
    some_int = reader.getInt();

    reader.close();
  }
}
Run Code Online (Sandbox Code Playgroud)

我想过在SomeObject中封装一个子对象,但这只是转移问题;或使用静态方法构造对象:

class SomeObject {
  private:
    const std::string some_string;
    const int some_int;

  public:
    static SomeObject unserialize(const char * input_filename){
      SomeReader reader = new SomeReader(input_filename);

      string str = reader.get_string();
      int i = reader.get_int();

      reader.close();

      SomeObject obj(str, i);
      return obj;
    };

    SomeObject(const std::string str, const int i) :
      some_string(str),
      some_int(i)
    {};
}
Run Code Online (Sandbox Code Playgroud)

有更好的解决方案吗?

谢谢。

Cas*_*sey 5

这是 C++11 构造函数委托的一个很好的应用:

class SomeObject {
  private:
    const std::string some_string;
    const int some_int;

  public:
    // The "real" constructor for SomeObject
    SomeObject(std::string str, const int i) :
      some_string{std::move(str)},
      some_int{i}
    {}

    // Deserialize from SomeReader (delegates to the primary constructor)
    SomeObject(SomeReader& reader) :
      SomeObject{reader.get_string(), reader.get_int()} {}

    // Deserialize from SomeReader (accepts rvalues,
    //   delegates to the lvalue constructor)
    SomeObject(SomeReader&& reader) :
      SomeObject{reader} {}

    // Deserialize from named file (delegates to the SomeReader&& constructor)
    SomeObject(const char* input_filename) :
      SomeObject{SomeReader{input_filename}} {}
};
Run Code Online (Sandbox Code Playgroud)