5

私は C++ で単純なスレッド化されたサーバー アプリケーションを作成しています。つまり、libconfig++ を使用して構成ファイルを解析しています。libconfig はマルチスレッドをサポートしていないため、「サポート」を実現するために 2 つのラッパー クラスを使用しています。ポイントは、そのうちの1つが失敗することです:

class app_config {
    friend class app_config_lock;
public:
    app_config(char *file) :
        cfg(new libconfig::Config()),
        mutex(new boost::mutex())
    {
        cfg->readFile(file);
    }

private:
    boost::shared_ptr<libconfig::Config> cfg;
    boost::shared_ptr<boost::mutex> mutex;
};

main.cpp ファイルから呼び出すと、ひどく失敗します。

app_main::app_main(int c, char **v) : argc(c), argv(v) {
    // here need code to parse arguments and pass configuration file!.
    try {
        config = app_config("mscs.cfg");
    } catch (libconfig::ParseException &e) {
        cout << "Parse error at line " << e.getLine() << ": " << e.getError() << endl;
        throw;
    } catch (libconfig::FileIOException &e) {
        cout << "Configuration file not found." << endl;
        throw;
    }
}

そしてそれは言います:

main.cpp: In constructor ‘app_main::app_main(int, char**)’:
main.cpp:38:54: error: no matching function for call to ‘app_config::app_config()’
main.cpp:38:54: note: candidates are:
../include/app_config.h:15:5: note: app_config::app_config(char*)
../include/app_config.h:15:5: note:   candidate expects 1 argument, 0 provided
../include/app_config.h:12:7: note: app_config::app_config(const app_config&)
../include/app_config.h:12:7: note:   candidate expects 1 argument, 0 provided
main.cpp:41:39: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings] (THIS CAN BE IGNORED, I WAS USING STD::STRING, YET CHANGED IT FOR TESTING PURPOSES)

私は明らかに引数を渡しているので、これは奇妙char *です.

いつものように、どんな助けでも大歓迎です。

ジュリアン。

4

2 に答える 2

10

構成をデフォルトで構築し、後で割り当てようとしています。しかし、デフォルトのコンストラクターがありません。

メンバ変数のコンストラクタに引数を渡す正しい方法は次のとおりです。

app_main::app_main(int c, char **v) : argc(c), argv(v), config("mscs.cfg")

関数 try-blockとして知られているものを使用して、例外をトラップすることもできます。http://www.gotw.ca/gotw/066.htmを参照してください。

最終的なコード:

app_main::app_main(int c, char **v)
try : argc(c), argv(v), config("mscs.cfg")
{
    // more constructor logic here
} catch (libconfig::ParseException &e) {
    cout << "Parse error at line " << e.getLine() << ": " << e.getError() << endl;
    throw;
} catch (libconfig::FileIOException &e) {
    cout << "Configuration file not found." << endl;
    throw;
}
于 2012-01-16T05:05:28.430 に答える
4

まず第一に、ミューテックスを動的に割り当てないでください。それは何の役にも立ちません。第二に、デフォルトで構築できないデータ メンバーがあり、それを ctor init リストで初期化していないためです。さらに、文字列リテラルを変数に割り当てないでください (本当に char ポインターを使いたい場合はそうchar*すべきです)。app_config(const char*)

代わりapp_main::app_mainに次のようになります。

app_main::app_main(int c, char **v) try
    : argc(c), argv(v), config("mscs.cfg") {
} catch (libconfig::ParseException &e) {
    cout << "Parse error at line " << e.getLine() << ": " << e.getError() << endl;
    throw;
} catch (libconfig::FileIOException &e) {
    cout << "Configuration file not found." << endl;
    throw;
}
于 2012-01-16T05:07:17.400 に答える