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
}
If the class is assignable/copy constructible you can just write
QFile file; //QFile class
int main()
{
file = QFile("C:\\example");
}
If not, you'll have to resort to other options:
QFile* file = 0;
int main()
{
file = new QFile("C:\\example");
//
delete file;
}
Or use boost::optional<QFile>
, std::shared_ptr<QFile>
, boost::scoped_ptr<QFile>
etc.
Due to the Static Initialization Fiasco you could want to write such a function:
static QFile& getFile()
{
static QFile s_file("C:\\example"); // initialized once due to being static
return s_file;
}
C++11 made such a function-local static initialization thread safe as well (quoting the C++0x draft n3242, §6.7:)
The same way:
// file.cpp
QFile file("C:\\example");
int main()
{
// use `file`
}
The constructors of all global objects execute before main()
is invoked (and inversely for destructors).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With