Apologies for such a basic question but I can’t figure it out. I know you can initialize a class like this:
QFile file("C:\\example");
But how would you initialize it from a global variable? For example:
QFile file; //QFile class
int main()
{
file = ?? //need to initialize 'file' with the QFile class
}
1. Straightforward answer
If the class is assignable/copy constructible you can just write
2. Use indirection
If not, you’ll have to resort to other options:
Or use
boost::optional<QFile>,std::shared_ptr<QFile>,boost::scoped_ptr<QFile>etc.3. Use singleton-related patterns:
Due to the Static Initialization Fiasco you could want to write such a function:
C++11 made such a function-local static initialization thread safe as well (quoting the C++0x draft n3242, §6.7:)