C++ init class 成员构造函数

C++ init class members constructor

我有两个 类、FooBarBar 包含 Foo 的一个实例,需要用文件中的一些数据对其进行初始化。初始化列表不应该是正确的,因为在初始化时计算机还不知道分配给 Foo 的值。

class Foo {
        int x;
    public:
        Foo(int new_x) : x(new_x) {}
};

class Bar {
        Foo FooInstance;
    public:
        Bar(const char * fileneme)
        /* Auto calls FooInstance() constructor, which does not exist
           Shoild I declare it to only avoid this error? */
        {
            /* [...] reading some data from the file */
            // Init a new FooInstance calling FooInstance(int)
            FooInstance = Foo(arg);
            /* Continue reading the file [...] */
        }
};

创建一个新对象,初始化它,然后将其复制到 FooInstance 中是一个不错的选择,如源代码所示?
或者可能将 FooInstance 声明为原始指针,然后用 new 初始化它? (并在 Bar 析构函数中销毁它)
FooInstance最优雅的初始化方式是什么?

如果可以计算必要的参数,则可以使用辅助函数:

class Bar
{
    static int ComputeFooArg() { /* ... */ };

public:
    Bar(const char * filename) : FooInstance(ComputeFooArg())
    {
        // ...
    }

    // ...
};

您可以使用委托构造函数(C++11 起)和额外函数:

MyDataFromFile ReadFile(const char* filename);

class Bar {
        Foo FooInstance;
    public:
        Bar(const char* fileneme) : Bar(ReadFile(filename))  {}

    private:
        Bar(const MyDataFromFile& data) : FooInstance(data.ForFoo)
        {
            // other stuff with MyDataFromFile.
        }
};