c++
Empty std::string in static method initialiser
I am using a static method to initialise the const fields of a class. The static method uses some const variables that are stored in a separate header file. Primitive types are correctly being passed to the static method, but the std::strings are being passed empty. I cannot understand why this is. After doing some searching I have stumbled upon something called the static initialiser fiasco, but I'm having trouble wrapping my head around it, and can't work out if it is to blame. As the the object is in global scope, is the problem that it is being 'setup' before the std::string class has been 'setup'? I have tried to replicate a minimal example below: // 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); } Thanks very much!
As the the object is in global scope, is the problem that it is being 'setup' before the std::string class has been 'setup'? Yes. Have your strings be function-statics, returned by reference from some function, instead. This is the traditional fix for the static initialisation order fiasco.
Related Links
Reading data through COM #C++ Windows
C++ map do plus plus without initialization
QMediaPlayer.play() doesn't work if I call a function with it
How are two strings compared?
How to quickly write large amounts of data into txt files
Can I check whether an address is in shared memory?
Poco C++ Libraries: “Not found: mysql”
boost:asio::read or boost:asio::async_read with timeout
sorting of vector of struct according the criteria and then display result
Qt 5.6 install issue
Game Engine: How to transpose Variables from structs: Coding practices
Visual C++ - Compile with BMI2
Iterator end() function not working with pointer arithmetic
makefile error no such file or directory
Why do we need to include the C or CPP declaration files during compilation and not the default libraries like iostream?
Memory leak with OpenCv 3.2.0 when in thread