OK maybe I clarify a bit, because now when I think of it, the problem is not necessarily specific to my
Texture class. It's more general.
Suppose I had the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
int main()
{
// Here I initialize some stuff.
SomeType1 var1(1,2,3);
SomeType2 var2(4,5,"abcd");
// Here I use it.
while (running) {
var1.use();
doSomethingWith(var2);
}
// And here they are automatically released.
}
|
so quite common programming pattern, nothing fancy here...
As long as you don't want to refactor it into separate functions for more readability and modularity, to get something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
// Here I initialize some stuff.
void init()
{
SomeType1 var1(1,2,3);
SomeType2 var2(4,5,"abcd");
}
// Here I use it.
void use()
{
var1.use(); // Well, not really: those names are unknown here.
doSomethingWith(var2);
}
int main()
{
init();
while (running) {
use();
}
// And here they are automatically released.
}
|
because now, of course,
var1 and
var2 are not known inside
use() :P
In order to make them known, I would have to make them global, something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
// Global definitions for sharing.
SomeType1 var1 = ...?; // WUT?
SomeType2 var2 = ...?;
// Here I initialize some stuff.
void init()
{
var1 = SomeType1(1,2,3); // Not really: too late for initialization :P
var2 = SomeType2(4,5,"abcd");
}
// Here I use it.
void use()
{
var1.use();
doSomethingWith(var2);
}
int main()
{
init();
while (running) {
use();
}
// And here they are automatically released.
}
|
but then, what initial values should I give them? :P I can't think of anything meaningful, because my
Texture objects can be initialized only when I already know their sizes and data, and only after I have the OpenGL context up and running, which is somewhere inside
init() and
no earlier!
I can't default-construct them at the global level, because they would have invalid state and any other methods called upon them would fail miserably :P (Not to mention that I can't call any functions to initialize their values on the global level either.)
On the other hand, inside
init(), it's already too late for any initialization if I created them globally :P Seems like a conundrum with no exit :/
I found this here piece of advice in one of Stroustrup's books:
Don't introduce a name until you have a suitable value for it. |
and I cannot agree more, because this makes a lot of sense, of course.
Unfortunately, Daddy Stroustrup doesn't say what to do when you need that name to be known somewhere else in the program, e.g. in another function, and how to make that name known there too :q
I feel stupid...