Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing global variable class

Tags:

c++

class

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
}
like image 763
123 Avatar asked Oct 27 '11 23:10

123


2 Answers

1. Straightforward answer

If the class is assignable/copy constructible you can just write

QFile file; //QFile class

int main()
{
    file = QFile("C:\\example");
}

2. Use indirection

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.

3. Use singleton-related patterns:

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:)

enter image description here

like image 148
sehe Avatar answered Nov 15 '22 21:11

sehe


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).

like image 38
Kerrek SB Avatar answered Nov 15 '22 22:11

Kerrek SB