2017-05-15 9 views
1

私はクラスのconstフィールドを初期化する静的メソッドを使用しています。静的メソッドは、別のヘッダーファイルに格納されているいくつかのconst変数を使用します。プリミティブ型は静的メソッドに正しく渡されますが、std :: stringsは空に渡されます。なぜこれが理解できないのですか?静的メソッドの初期化子で空のstd :: string

いくつかの検索をした後、私は静的な初期化子の失敗と遭遇しましたが、私の頭をラップするのに問題があります。オブジェクトがグローバルスコープにあるので、std :: stringクラスが 'setup'される前に 'setup'されているという問題がありますか?

私は以下の最小限の例を再現しようとしている:

// File: settings.hpp 
#include <string> 
const std::string TERMINAL_STRING "Printing to the terminal"; 
const std::string FILE_STRING "Printing to a file"; 


// File: printer.hpp 
#include <string> 
#include <iostream> 

class Printer 
{ 
    private: 
     const std::string welcomeMessage; 
     static std::string initWelcomeMessage(std::ostream&); 

    public: 
     Printer(std::ostream&); 
} 

extern Printer::print; 


// File: printer.cpp 
#include "settings.hpp" 

std::string Printer::initWelcomeMessage(std::ostream &outStream) 
{ 
    if (&outStream == &std::cout) 
    { 
     return (TERMINAL_STRING); 
    } 
    else 
    { 
     return (FILE_STRING); 
    } 
} 

Printer::Printer(std::ostream &outStream) : 
    message(initWelcomeMessage(outStream) 
{ 
    outStream << welcomeMessage << std::endl; 

    return; 
} 


// File: main.cpp 
#include "printer.hpp" 

printer print(std::cout); 

int main() 
{ 
    return (0); 
} 

どうもありがとうございました!

答えて

2

オブジェクトがグローバルスコープにあるので、std :: stringクラスが 'setup'される前に 'setup'されているという問題がありますか?

はい。

文字列を関数にする - static、代わりに関数からの参照によって返されます。

これは静的な初期化順序の失敗の従来の修正です。

+0

ご確認いただきありがとうございます。 – user7119460

関連する問題